Skip to content

Instantly share code, notes, and snippets.

@MKRhere
Last active May 23, 2021 20:48
Show Gist options
  • Save MKRhere/98af70ba884aa7b8c57c0c4f33c04232 to your computer and use it in GitHub Desktop.
Save MKRhere/98af70ba884aa7b8c57c0c4f33c04232 to your computer and use it in GitHub Desktop.
Early returnable Fold
class FoldBreak <T> {
constructor(public value: T) {};
};
const foldBreak = <T>(value: T) => new FoldBreak(value);
export const fold = Object.assign(<X, Acc>(
reducer: (acc: Acc, x: X) => Acc | FoldBreak<Acc>,
init: Acc,
xs: X[],
): Acc => {
let acc: Acc | FoldBreak<Acc> = init;
for (const x of xs) {
acc = reducer(acc, x);
if (acc instanceof FoldBreak) return acc.value;
}
return acc;
}, { break: foldBreak });
const folded = fold(
(acc, item) => item > 3 ? fold.break(acc) : acc.concat(item),
[] as number[],
[1, 2, 3, 4, 5]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment