Last active
February 17, 2023 16:13
-
-
Save pigoz/d06f0bd330e9cb3f8e5846af2e672765 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { pipe } from '@fp-ts/core/Function'; | |
import * as A from '@fp-ts/core/ReadonlyArray'; | |
import * as HashMap from '@effect/data/HashMap'; | |
import { dual } from '@fp-ts/core/Function'; | |
const compare = { | |
number: (a: number, b: number) => a - b, | |
string: (a: string, b: string) => | |
a.localeCompare(b, 'en', { sensitivity: 'base' }), | |
Date: (a: Date, b: Date) => a.getTime() - b.getTime(), | |
} as const; | |
function _sort<A1, B1>( | |
self: ReadonlyArray<A1>, | |
compare: (a: B1, b: B1) => number, | |
mapper: (value: A1) => B1, | |
): ReadonlyArray<A1> { | |
return self | |
.map((value, idx) => [idx, mapper(value)] as const) | |
.sort((a, b) => compare(a[1], b[1])) | |
.map(x => x[0]) | |
.map(_ => self[_]!); | |
} | |
export const sort: { | |
<A1, B1>(compare: (a: B1, b: B1) => number, mapper: (value: A1) => B1): ( | |
self: ReadonlyArray<A1>, | |
) => ReadonlyArray<A1>; | |
<A1, B1>( | |
self: ReadonlyArray<A1>, | |
compare: (a: B1, b: B1) => number, | |
mapper: (value: A1) => B1, | |
): ReadonlyArray<A1>; | |
} & typeof compare = Object.assign(dual(3, _sort), compare); | |
function _uniq<A1, B1>( | |
self: ReadonlyArray<A1>, | |
mapper: (value: A1) => B1, | |
): ReadonlyArray<A1> { | |
return pipe( | |
self, | |
A.map(item => [mapper(item), item] as const), | |
HashMap.fromIterable, | |
HashMap.values, | |
values => [...values], | |
); | |
} | |
export const uniq: { | |
<A1, B1>(mapper: (value: A1) => B1): ( | |
self: ReadonlyArray<A1>, | |
) => ReadonlyArray<A1>; | |
<A1, B1>( | |
self: ReadonlyArray<A1>, | |
mapper: (value: A1) => B1, | |
): ReadonlyArray<A1>; | |
} = dual(2, _uniq); | |
/* | |
const example = [{ foo: 1 }, { foo: 2 }, { foo: 1 }, { foo: 3 }]; | |
const sorted = pipe( | |
example, | |
sort(sort.number, _ => _.foo) | |
); | |
const deduped = pipe( | |
example, | |
uniq(sort.number, _ => _.foo) | |
); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment