Skip to content

Latest commit

 

History

History
31 lines (26 loc) · 1.23 KB

aperture.md

File metadata and controls

31 lines (26 loc) · 1.23 KB
title tags author_title author_url author_image_url description image
aperture
array,intermediate
Deepak Vishwakarma
Implementation of "aperture" in typescript, javascript and deno.

TS JS Deno

Returns an array of n-tuples of consecutive elements.

Use Array.prototype.slice() and Array.prototype.map() to create an array of appropriate length and populate it with n-tuples of consecutive elements from arr. If n is greater than the length of arr, return an empty array.

const aperture = <T = any>(n: number, arr: T[]) =>
  n >= arr.length
    ? []
    : arr.slice(n - 1).map((v, i) => [...arr.slice(i, i + n - 1), v]);
aperture(2, [1, 2, 3, 4]); // [[1, 2], [2, 3], [3, 4]]
aperture(3, [1, 2, 3, 4]); // [[1, 2, 3], [2, 3, 4]]
aperture(5, [1, 2, 3, 4]); // [1, 2, 3, 4]