Skip to content

Instantly share code, notes, and snippets.

@pigoz
Last active February 17, 2023 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pigoz/d06f0bd330e9cb3f8e5846af2e672765 to your computer and use it in GitHub Desktop.
Save pigoz/d06f0bd330e9cb3f8e5846af2e672765 to your computer and use it in GitHub Desktop.
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