atlas-for-window
Generalizes iterating over an array with a sliding window.
install
npm install --save atlas-for-window
why
Sometimes you need to iterate over a window of values in an array, and do something "for each window":
// window size = 2123456 // main array12 // 1st window 23 // 2nd window 34 // 3rd window 45 // 4th window 56 // 5th window
We'd like to do this without polluting our business logic with iteration logic. This library provides a clean API for iterating over n-windows in an array.
examples
highly readable
A single argument gives you a physical window to work with:
const forWindow = ;const myArray = "a" "b" "c" "d"; // iterate over all 2-windows in myArray // ['a', 'b']// ['b', 'c']// ['c', 'd']
highly performant
Slicing is expensive. Non-unary iterator functions will be given the start and end indexes of the window, which is much, much faster than slicing:
nullary iterator function
... // 0 2// 1 3// 2 4
binary iterator function
... // 0 2// 1 3// 2 4
variadic iterator function
... // 0 2// 1 3// 2 4
using start and end indexes
Please note that the end index is non-inclusive, allowing you to use the familiar iteration syntax:
... // ['a', 'b']// ['b', 'c']// ['c', 'd']
caveats
You don't need to worry about the edge cases. If the desired window size is greater or equal to the parent array size, the iterator will be run exactly once: either with the parent array as the window argument in the case of a unary iterator, or with the arguments (0, parentArray.length)
in the case of a non-unary iterator.