Skip to content

Instantly share code, notes, and snippets.

@fredericoo
Created September 17, 2020 15:43
Show Gist options
  • Save fredericoo/9b582e6b48ea8939fe4cc847380fea7d to your computer and use it in GitHub Desktop.
Save fredericoo/9b582e6b48ea8939fe4cc847380fea7d to your computer and use it in GitHub Desktop.
function aperture(n, arr) {
if (n > arr.length) {
return [];
} else {
return arr.slice(n - 1) // makes a COPY (does NOT modify arr) starting at the index of n - 1 (that's the only argument of slice in this case).
// slice is applied here basically to set the returned array with the proper length. For tuples it'd be equal to n minus one, always.
.map( // Manipulates array in previous line going through each of the elements. Renamed variables for your better understanding
// going through each of the n-1 array, it'll modify each entry to accomodate a different value.
(currentValue, currentIndex) => arr.slice(currentIndex, currentIndex + n) // each element is then replaced by a sliced arr (the original one, in the argument) starting at currentIndex (so first item would be 0, the beginning of arr) and stopping at currentIndex + n (here's the n-tuples magic!)
// notice how currentValue (the value of the instance being analysed in the array) is COMPLETELY disregarded? that's very curious, uncommon and useful: usually if you'd want to multiply every item in an array by two, you'd use the current value, but in this case we're completely OVERWRITING the contents of each element of the array. The very first splice did only set the correct array length, but contents within it are disregarded.
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment