Last active
May 23, 2021 20:48
-
-
Save MKRhere/98af70ba884aa7b8c57c0c4f33c04232 to your computer and use it in GitHub Desktop.
Early returnable Fold
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
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