@jcayzac/utils-sorters
v1.1.0
Published
Composable sorting algorithms for sort() or toSorted().
Downloads
11
Maintainers
Readme
@jcayzac/utils-sorters
Composable sorting algorithms for
sort()
ortoSorted()
.
Installation
# pnpm
pnpm add @jcayzac/utils-sorters
# bun
bunx add @jcayzac/utils-sorters
# npm
npx add @jcayzac/utils-sorters
# yarn
yarn add @jcayzac/utils-sorters
# deno
deno add npm:@jcayzac/utils-sorters
Usage
import * as sorters from '@jcayzac/utils-sorters'
const data = [{a:'bbb',b:20},{a:'ccc',b:4},{a:'aab',b:2},{a:'zzz',b:8},{a:'fff',b:18}]
// Sort by 'a' property, reverse-lexicographically
data.toSorted(sorters.reversed(sorters.lexicographic(({a}) => a)))
/* output: */ [
{ a: "zzz", b: 8 },
{ a: "fff", b: 18 },
{ a: "ccc", b: 4 },
{ a: "bbb", b: 20 },
{ a: "aab", b: 2 }
]
// Sort by 'b' property, numerically, in descending order
data.toSorted(sorters.descending(({b}) => b))
/* output: */ [
{ a: "bbb", b: 20 },
{ a: "fff", b: 18 },
{ a: "zzz", b: 8 },
{ a: "ccc", b: 4 },
{ a: "aab", b: 2 }
]
// Same thing, but done differently
data.toSorted(sorters.reversed(sorters.ascending(({b}) => b)))
// Sort lexicographically by `${a} = ${b}`
data.toSorted(sorters.lexicographic(({a,b}) => `${a} = ${b}`))
/* output: */ [
{ a: "aab", b: 2 },
{ a: "bbb", b: 20 },
{ a: "ccc", b: 4 },
{ a: "fff", b: 18 },
{ a: "zzz", b: 8 }
]
// Sort dates in descending order
// If no transformer is provided, both ascending() and descending() just coerce items to numbers
const dates = [new Date('2021-01-01'), new Date('2020-01-01'), new Date('2022-01-01')]
dates.toSorted(sorters.descending())
/* output: */ [
2022-01-01T00:00:00.000Z,
2021-01-01T00:00:00.000Z,
2020-01-01T00:00:00.000Z
]
// Sort URLs lexicographically
// If no transformer is provided, lexicographic() just coerces items to strings
const urls = [
new URL('https://example.xyz/foo'),
new URL('https://example.com/foo'),
new URL('https://example.net/foo'),
new URL('https://example.org/foo'),
new URL('https://example.dev/foo'),
]
urls.toSorted(sorters.lexicographic())
/* output: */ [
new URL('https://example.com/foo'),
new URL('https://example.dev/foo'),
new URL('https://example.net/foo'),
new URL('https://example.org/foo'),
new URL('https://example.xyz/foo')
]
Like it? Buy me a coffee!
If you like anything here, consider buying me a coffee using one of the following platforms: