diff options
-rw-r--r-- | src/utils.mjs | 2 | ||||
-rw-r--r-- | tests/js/utils.mjs | 20 |
2 files changed, 22 insertions, 0 deletions
diff --git a/src/utils.mjs b/src/utils.mjs index cde6934..30a0f1a 100644 --- a/src/utils.mjs +++ b/src/utils.mjs @@ -82,3 +82,5 @@ export const partial = (fn, ...startArgs) => fn(...startArgs, ...endArgs); export const strSortFn = (a, b) => a.localeCompare(b, "POSIX"); + +export const undefinedAsNull = x => x === undefined ? null : x; diff --git a/tests/js/utils.mjs b/tests/js/utils.mjs index 178f6c8..d16bae8 100644 --- a/tests/js/utils.mjs +++ b/tests/js/utils.mjs @@ -11,6 +11,7 @@ import { promisify, partial, strSortFn, + undefinedAsNull, } from "../../src/utils.mjs"; const test_eq = t => { @@ -361,6 +362,24 @@ const test_strSortFn = t => { }); }; +const test_undefinedAsNull = t => { + t.start("undefinedAsNull()"); + + t.test("null for undefined or null", () => { + assert.equal(undefinedAsNull(undefined), null); + assert.equal(undefinedAsNull(null), null); + }); + + t.test("identity otherwise", () => { + const expected = [ + " ", "", 0, 1, -1.1, true, false, + [], [ "" ], {}, { k: "v" }, + ]; + const given = expected.map(undefinedAsNull); + assert.deepEqual(given, expected); + }); +}; + await runner.runTests([ test_eq, @@ -372,4 +391,5 @@ await runner.runTests([ test_promisify, test_partial, test_strSortFn, + test_undefinedAsNull, ]); |