From 67191c9b2717e300237f4e0bdebe7cdc7ba2fb96 Mon Sep 17 00:00:00 2001 From: Per Cederberg Date: Sat, 7 Dec 2024 13:23:56 +0100 Subject: [PATCH] js: Improved null/undefined/NaN handling in rapidcontext.data.compare() --- src/plugin/system/files/js/rapidcontext/data.mjs | 10 ++++++++-- test/src/js/rapidcontext/data.test.mjs | 6 +++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/plugin/system/files/js/rapidcontext/data.mjs b/src/plugin/system/files/js/rapidcontext/data.mjs index fecbf03c..8133fe04 100644 --- a/src/plugin/system/files/js/rapidcontext/data.mjs +++ b/src/plugin/system/files/js/rapidcontext/data.mjs @@ -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']; @@ -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); + } } /** diff --git a/test/src/js/rapidcontext/data.test.mjs b/test/src/js/rapidcontext/data.test.mjs index 50bfdacc..f50c2390 100644 --- a/test/src/js/rapidcontext/data.test.mjs +++ b/test/src/js/rapidcontext/data.test.mjs @@ -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);