From 55f2891fd6004017fe7df74945eee5e323c01621 Mon Sep 17 00:00:00 2001 From: Tse Kit Yam Date: Wed, 13 Oct 2021 09:34:13 +0800 Subject: [PATCH] Allow comparing between number and string --- README.md | 2 +- src/index.spec.ts | 4 +--- src/index.ts | 8 ++++---- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 28d841d..436dbfe 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ console.log(["item20", "item19", "item1", "item10", "item2"].sort(compareFn)); [CodeSandbox](https://codesandbox.io/s/alphanum-compare-demo-bfhln) -### `compareFn(a: string, b: string, opts?: Options): number` +### `compareFn(a: number | string, b: number | string, opts?: Options): number` It returns a negative value if first argument is less than second argument, zero if they're equal and a positive value otherwise. diff --git a/src/index.spec.ts b/src/index.spec.ts index 9b56b2d..6ba892d 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -363,9 +363,7 @@ describe("sorting", function () { tests.forEach((test) => { it(test.message, () => { assert.deepEqual( - test.fixture.sort((a, b) => - compareFn(a.toString(), b.toString(), test.options) - ), + test.fixture.sort((a, b) => compareFn(a, b, test.options)), test.expected ); }); diff --git a/src/index.ts b/src/index.ts index 002b3cc..2d6a464 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,15 +15,15 @@ function isSign(code: number) { } function compare( - a: string, - b: string, + a: number | string, + b: number | string, opts?: { insensitive?: boolean; sign?: boolean } ): number { const checkCase = opts?.insensitive ?? false; const checkSign = opts?.sign ?? false; - const av = checkCase ? a.toLowerCase() : a; - const bv = checkCase ? b.toLowerCase() : b; + const av = checkCase ? `${a}`.toLowerCase() : `${a}`; + const bv = checkCase ? `${b}`.toLowerCase() : `${b}`; let ia = 0; let ib = 0; const ma = av.length;