list-pairs
v0.1.3
Published
Making lists of pairs easy
Maintainers
Readme
List Pairs
Form pairs using all the elements in an array.
[1, 2, 4, 1, 3] //=> [ [ 1, 2 ],
[ 1, 4 ],
[ 1, 3 ],
[ 2, 4 ],
[ 2, 3 ],
[ 4, 3 ] ]You can selectively choose whether to allow pairs formed from the same elements ([a, a]), whether to allow duplicates ([a, b] and [a, b]), or symmetric cases ([a, b] and [b, a]).
If the original array is an array of objects, the resulting array contains references to the originals.
Install
$ npm install list-pairsUsage
Given an input array, the function uniquePairs generates pairs with all the unique combinations. The array can have any type.
const numbers = [1, 2, 3];
await uniquePairs(numbers);
//=> [ [ 1, 2 ], [ 1, 3 ], [ 2, 3 ] ]
const objects = [{ a: 1 }, { b: 2 }, { c: 3 }];
await uniquePairs(objects);
//=> [
// [ { a: 1 }, { b: 2 } ],
// [ { a: 1 }, { c: 3 } ],
// [ { b: 2 }, { c: 3 } ]
// ]You can also have more control using the individual functions noSelf, noDuplicates, and noReverse.
Here is another example.
const numbers = [1, 1, 2];
const allPairs = await pair(numbers);
//=> [ [ 1, 1 ], [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 1, 1 ], [ 1, 2 ], [ 2, 1 ], [ 2, 1 ], [ 2, 2 ] ]
const noSelfPairs = noSelf(allPairs);
//=> [ [ 1, 2 ], [ 1, 2 ], [ 2, 1 ], [ 2, 1 ] ]
const noDuplicatePairs = noDuplicates(noSelfPairs);
//=> [ [ 1, 2 ], [ 2, 1 ] ]
const finalPairs = noReverse(noDuplicatePairs);
//=> [ [ 1, 2 ] ]
// This could have been achieved with a single call
await uniquePairs(numbers);
//=> [ [ 1, 2 ] ]
// ... or by concatenating the individual functions
await pair(numbers) //
.then(noSelf)
.then(noDuplicates)
.then(noReverse);
//=> [ [ 1, 2 ] ]Refer to this file for a working example.
License
MIT
Credits
Developed by MAKinteract with ♥️.
