Skip to content

Commit

Permalink
js: Improved null/undefined/NaN handling in rapidcontext.data.compare()
Browse files Browse the repository at this point in the history
  • Loading branch information
cederberg committed Dec 7, 2024
1 parent 169f5ce commit 67191c9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/plugin/system/files/js/rapidcontext/data.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* @namespace RapidContext.Data
*/

import { isNil, isFunction, isObject, isArrayLike, isIterable, hasProperty, hasValue } from './fn.mjs';
import { isNil, isFunction, isNumber, isObject, isArrayLike, isIterable, hasProperty, hasValue } from './fn.mjs';

const OFF = ['null', 'undefined', '0', 'f', 'false', 'off', 'n', 'no'];

Expand Down Expand Up @@ -380,7 +380,13 @@ export function compare(valueOf, a, b) {
a = valueOf(a);
b = valueOf(b);
}
return a < b ? -1 : (a > b ? 1 : 0);
let aNil = isNil(a) || (isNumber(a) && isNaN(a));
let bNil = isNil(b) || (isNumber(b) && isNaN(b));
if (aNil || bNil) {
return (aNil && bNil) ? 0 : (aNil ? -1 : 1);
} else {
return (a < b) ? -1 : (a > b ? 1 : 0);
}
}

/**
Expand Down
6 changes: 5 additions & 1 deletion test/src/js/rapidcontext/data.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -195,10 +195,14 @@ test('data.uniq()', () => {

test('data.compare()', () => {
assert.strictEqual(data.compare(null, undefined), 0);
assert.strictEqual(data.compare(null, NaN), 0);
assert.strictEqual(data.compare(undefined, null), 0);
assert.strictEqual(data.compare(undefined, NaN), 0);
assert.strictEqual(data.compare(1, 1), 0);
assert.strictEqual(data.compare(1, 42), -1);
assert.strictEqual(data.compare(1, NaN), 0);
assert.strictEqual(data.compare(1, NaN), 1);
assert.strictEqual(data.compare(null, 1), -1);
assert.strictEqual(data.compare('', 'abc'), -1);
assert.strictEqual(data.compare('abc', 'abc'), 0);
assert.strictEqual(data.compare('abc', 'cde'), -1);
assert.strictEqual(data.compare('cde', 'abc'), 1);
Expand Down

0 comments on commit 67191c9

Please sign in to comment.