From 21c9abbbcf16ae98c9acb611ed79b2c3a83cc18e Mon Sep 17 00:00:00 2001 From: bcho892 Date: Sun, 18 Aug 2024 20:52:56 +1200 Subject: [PATCH] update string compare method --- client/src/services/Admin/AdminUtils.test.ts | 34 ++++++++++++++++++++ client/src/services/Admin/AdminUtils.ts | 17 ++++------ 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/client/src/services/Admin/AdminUtils.test.ts b/client/src/services/Admin/AdminUtils.test.ts index 3599f1f72..0032be5ef 100644 --- a/client/src/services/Admin/AdminUtils.test.ts +++ b/client/src/services/Admin/AdminUtils.test.ts @@ -47,4 +47,38 @@ describe("compareStrings", () => { it("should return 0 for equal strings", () => { expect(compareStrings("abbb", "abbb")).toEqual(0) }) + + it("should handle empty strings correctly", () => { + expect(compareStrings("", "a")).toBeLessThan(0) + expect(compareStrings("a", "")).toBeGreaterThan(0) + expect(compareStrings("", "")).toEqual(0) + }) + + it("should handle strings with different cases", () => { + expect(compareStrings("abc", "ABC")).toBeGreaterThan(0) // Assuming case-sensitive comparison + expect(compareStrings("ABC", "abc")).toBeLessThan(0) // Assuming case-sensitive comparison + }) + + it("should handle strings with special characters", () => { + expect(compareStrings("abc!", "abc")).toBeGreaterThan(0) + expect(compareStrings("abc", "abc!")).toBeLessThan(0) + expect(compareStrings("abc!", "abc!")).toEqual(0) + }) + + it("should handle strings with numbers", () => { + expect(compareStrings("abc1", "abc2")).toBeLessThan(0) + expect(compareStrings("abc2", "abc1")).toBeGreaterThan(0) + expect(compareStrings("abc1", "abc1")).toEqual(0) + }) + + it("should handle strings with spaces", () => { + expect(compareStrings("abc ", "abc")).toBeGreaterThan(0) + expect(compareStrings("abc", "abc ")).toBeLessThan(0) + expect(compareStrings("abc ", "abc ")).toEqual(0) + }) + + it("should handle strings with different lengths", () => { + expect(compareStrings("abc", "abcd")).toBeLessThan(0) + expect(compareStrings("abcd", "abc")).toBeGreaterThan(0) + }) }) diff --git a/client/src/services/Admin/AdminUtils.ts b/client/src/services/Admin/AdminUtils.ts index d81fd7746..0c527ad79 100644 --- a/client/src/services/Admin/AdminUtils.ts +++ b/client/src/services/Admin/AdminUtils.ts @@ -40,16 +40,11 @@ export function replaceUserInPage( * @returns `0` if `a` and `b` are equal strings */ export function compareStrings(a: string, b: string) { - for (let i = 0; i < Math.min(a.length, b.length); ++i) { - const charCodeA = a.charCodeAt(i) - const charCodeB = b.charCodeAt(i) - - const difference = charCodeA - charCodeB - - if (difference !== 0) { - return difference - } + if (a < b) { + return -1 + } else if (a > b) { + return 1 + } else { + return 0 } - - return 0 }