Skip to content

Instantly share code, notes, and snippets.

@fResult
Last active March 26, 2023 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fResult/11c7548d1b3335bd5f23d9c8d3deb5ae to your computer and use it in GitHub Desktop.
Save fResult/11c7548d1b3335bd5f23d9c8d3deb5ae to your computer and use it in GitHub Desktop.
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