Created
March 7, 2024 20:26
-
-
Save BRonen/d753e61bf8e030efd8312edd9a380680 to your computer and use it in GitHub Desktop.
A brief snippet doing an iterable structure with recursion instead of loops
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
type Iter<A> = () => A | null; | |
const array_to_iter = <A>(arr: A[]): Iter<A> => { | |
let index = 0; | |
return () => { | |
const el = arr[index]; | |
index += 1; | |
return el; | |
} | |
}; | |
const for_iter = <A>(iter: () => A | null, cb: (el: A) => unknown): void => { | |
const el = iter(); | |
if(!el) return; | |
cb(el); | |
for_iter(iter, cb); | |
}; | |
const map_iter = <A, B>(iter: () => A | null, cb: (el: A) => B): B[] => { | |
let acc = [] satisfies B[]; | |
const el = iter(); | |
if(!el) return acc; | |
return [cb(el), ...map_iter(iter, cb)]; | |
} | |
const reduce_iter = <A, B>(iter: () => A | null, cb: (el: A, acc: B) => B, acc: B): B => { | |
const el = iter(); | |
if(!el) return acc; | |
return reduce_iter(iter, cb, cb(el, acc)); | |
} | |
for_iter(array_to_iter(["a5", "b4", "c3", "d2", "e1"]), console.log); | |
console.log(map_iter(array_to_iter(["a5", "b4", "c3", "d2", "e1"]), (el) => `${el} - mapped`)); | |
console.log(reduce_iter(array_to_iter([100, 10, 1]), (el, acc) => (el + acc), 0)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment