Skip to content

Get a specified amount of items when iterating over a JavaScript array, instead of just a single item that native arrays provide

License

Notifications You must be signed in to change notification settings

chalu/n-tuple-array

Repository files navigation

n-tuple-array

Get a configurable amount of items when iterating over a JavaScript array, instead of a single item that arrays provide per iteration, by default.

Put differently, easily and safely retrieve a configurable number of items from an array, without having to manipulate array bounds or indices.

Motivation

Imagine that you received a large collection of coordinates (latitude and longitude), but they were sent as a flat array of values to speed up the data transfer.

n-tuple-array can help you get out the coordinates in pairs (i.e their logical representation), such that you'd easily go

from

// flat coordinates
["5.7225", "-9.6273", "2.68452", "-30.9501", ...]

to

// coordinates in pairs
[["5.7225", "-9.6273"], ["2.68452", "-30.9501"], ...]

using

// the iterable will generate pairs by default
const coordsIterable = tuplesFromArray({ list: flatCoords });

// with for..of, get pairs as ["5.7225", "-9.6273"] ...
for (const pair of coordsIterable) {
    console.log(pair);
}

// OR 
// manipulate pairs with regular array 
// functions like map, filter, forEach ...
const coordsInPairs = Array.from(coordsIterable);
console.log(Array.isArray(coordsInPairs));   // true
coordsInPairs
    .map(pair => {
        // pair is ["5.7225", "-9.6273"] ...
        return myTransform(pair);
    })
	.forEach((pair) => {
        // pair is ["5.7225", "-9.6273"] ...
        placeOnMap(pair);
    });

Setup & Usage

npm install @chalu/n-tuple-array
const { tuplesFromArray } = require('@chalu/n-tuple-array');

// some setup
const numbers = Array.from({length: 100}, (_, i) => i + 1);
const isEven = (item) => {
    if (
        !item
        || typeof item !== 'number'
        || item % 2 !== 0
    ) return false;

    return true;
};

// use the lib, get batches of <= 5 nums
// from the collection in numbers above
const quintetIterator = tuplesFromArray({
    list: numbers, maxItems: 5, match: isEven
});

// since quintetIterator uses the isEven match
// function, give us only even numbers in fives
for (const quintet of quintetIterator) {
    // prints [ 2, 4, 6, 8, 10 ] ... [ 92, 94, 96, 98, 100 ]
	console.log(quintet);
}

Some Real World Examples

1. Wole Joko

I first tried my hands on this concept when fleshing out wole-joko, which strated as a live coding task I was asked to do in an engineering manager interview :man_shrugging It was a simulation of people entering an event hall to get seated, but only two could get in at a time - https://wole-joko.netlify.app/

2. Execute max of N async tasks at the same time

The below was adapted for more concise terminal output

n-tuple-array solution. View code here


n-tuple-array solution demo

See more examples in src/examples

About

Get a specified amount of items when iterating over a JavaScript array, instead of just a single item that native arrays provide

Resources

License

Stars

Watchers

Forks

Packages

No packages published