Skip to content

Instantly share code, notes, and snippets.

@joshwashywash
Last active April 7, 2023 19:53
Show Gist options
  • Save joshwashywash/8f3b4d1cd34ec2b3f32591e61ed321b7 to your computer and use it in GitHub Desktop.
Save joshwashywash/8f3b4d1cd34ec2b3f32591e61ed321b7 to your computer and use it in GitHub Desktop.
aperture implementation in TypeScript

This is named after Ramda's aperture function https://ramdajs.com/docs/#aperture.

const aperture = (n: number) =>
	<T>(xs: T[]): T[][] =>
		n < 1 || n > xs.length
			? []
			: Array.from({ length: xs.length - n + 1 }, (_, i) => xs.slice(i, i + n));

Example:

const pairs = aperture(2)([0, 1, 2, 3, 4]);
console.log(pairs);
// [[0, 1], [1, 2], [2, 3], [3, 4]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment