Skip to content

Instantly share code, notes, and snippets.

@JoseHdez2
Last active August 3, 2022 12:27
Show Gist options
  • Save JoseHdez2/0048517fd4ebefb1a2057d5f412cc281 to your computer and use it in GitHub Desktop.
Save JoseHdez2/0048517fd4ebefb1a2057d5f412cc281 to your computer and use it in GitHub Desktop.
Generic version of String.join().
/** `zip([a, b, c], [1, 2, 3] => [[a, 1], [b, 2], [c, 3]])` */
const zip = (a: Array<any>, b: Array<any>) =>
Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);
/** Generic version of String.join(). Add a separator element between each of the elements. */
const join = (a: Array<any>, separator: any) =>
zip(a, Array(a.length - 1).fill(separator))
.flat()
.splice(-1);
console.log(join([1, 2, 3, 4, 5], "|"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment