Skip to content

tsekityam/alphanum-compare

Repository files navigation

alphanum-compare

npm version Node.js CI codecov Known Vulnerabilities FOSSA Status

Compare function extrated from alphanum-sort. It can be used as compareFunction in Array.prototype.sort().

Install

yarn add alphanum-compare

Usage

import compareFn from "alphanum-compare";

console.log("5".localeCompare("10")); // 1, NO GOOD
console.log(compareFn("5", "10")); // -1, GOOD

console.log(compareFn("-5", "5")); // 1, NO GOOD
console.log(compareFn("-5", "5", { sign: true })); // -1, GOOD

console.log(["item20", "item19", "item1", "item10", "item2"].sort(compareFn));
// ['item1', 'item2', 'item10', 'item19', 'item20']

CodeSandbox

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.

Options

  • insensitive?: boolean

    Compares items case insensitively. (Default: false)

  • sign?: boolean

    Allows + and - characters before numbers. (Default: false)

License

FOSSA Status