Skip to content

Instantly share code, notes, and snippets.

@mkulke
Last active April 28, 2018 14:10
Show Gist options
  • Save mkulke/6e043486ce6d467eebcb70d5ff4deb6d to your computer and use it in GitHub Desktop.
Save mkulke/6e043486ce6d467eebcb70d5ff4deb6d to your computer and use it in GitHub Desktop.
lackluster partition with conditional types
type Pred<T, U extends T> = (v: T) => v is U;
function filter<T, U extends T>(coll: T[], pred: Pred<T, U>): U[] {
const seed: U[] = [];
return coll.reduce((acc: U[], val: T) => {
if (pred(val)) {
return [...acc, val];
}
return acc;
}, seed);
}
type Tuple<T, U> = [T, U];
type ArrayTuple<T, U> = Tuple<T[], U[]>;
type Partition<T, U extends T> = ArrayTuple<U, Exclude<T, U>>;
function partition<T, U extends T>(coll: T[], pred: Pred<T, U>): Partition<T, U> {
const yes = filter(coll, pred);
const antiPred: Pred<T, Exclude<T, U>> = (val: T): val is Exclude<T, U> => !pred(val);
const no = filter(coll, antiPred);
return [yes, no];
// const seed: Partition<T, U> = [[], []];
// return coll.reduce((acc: Partition<T, U>, val: T) => {
// const [yes, no] = acc;
// if (pred(val)) {
// const p: Partition<T, U> = [[...yes, val], no];
// return p;
// }
// const p: Partition<T, U> = [yes, [...no, val]]; // does not compile b/c val is T
// return p;
// }, seed);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment