Test name | Executions per second |
---|---|
compareString() | 30376498.0 Ops/sec |
compareString2() | 7690405.0 Ops/sec |
<!--your preparation HTML code goes here-->
const compareString = (a, b) => {
if (a === null && b !== null) {
return 1;
} else if (a !== null && b === null) {
return -1;
} else if (a !== null && b !== null) {
return a.toLowerCase() > b.toLowerCase() ? 1 : a.toLowerCase() === b.toLowerCase() ? 0 : -1;
} else {
return 0;
}
};
const compareString2 = (a, b) => {
const s1 = a ? [a.toLowerCase()].reduce((prev, char) => prev + char.charCodeAt(0), 0) : 0;
const s2 = b ? [b.toLowerCase()].reduce((prev, char) => prev + char.charCodeAt(0), 0) : 0;
return a && b ? Math.sign(s1 - s2) : Math.sign(s2 - s1);
};
compareString("Anita", "Ben");
compareString2("Anita", "Ben");