Last active
March 26, 2023 08:51
-
-
Save fResult/11c7548d1b3335bd5f23d9c8d3deb5ae to your computer and use it in GitHub Desktop.
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
function zip(xs, ys) { | |
if (xs.length < ys.length) { | |
return xs.map((x, idx) => [x, ys[idx]]) | |
} else { | |
return ys.map((y, idx) => [xs[idx], y]) | |
} | |
} | |
// FP Style | |
function head<T>(xs: T[]): T { | |
return xs[0] | |
} | |
function tail<T>(xs: T[]): T[] { | |
return xs.slice(1) | |
} | |
function zip<T, U>(xs: T[], ys: U[], zipped: [T, U][] = []): [T, U][] { | |
if (xs.length === 0 || ys.length === 0) return zipped | |
return zip(tail(xs), tail(ys), [...zipped, [head(xs), head(ys)]]) | |
} | |
// - Currying | |
function zip<U>(ys: U[]) { | |
return function forXs<T>(xs: T[]) { | |
return function appliedTailCall(zipped: [T, U][] = []): [T, U][] { | |
if (xs.length === 0 || ys.length === 0) return zipped | |
return zip(tail(ys))(tail(xs))([...zipped, [head(xs), head(ys)]]) | |
} | |
} | |
} | |
// - w/o proper tail call | |
function zip<T, U>(xs: T[], ys: U[]): [T, U][] { | |
if (xs.length === 0 || ys.length === 0) return [] | |
return [[head(xs), head(ys)], ...zip(tail(xs), tail(ys))] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment