added .zip(..) to Arrays...

Signed-off-by: Alex A. Naanou <alex.nanou@gmail.com>
This commit is contained in:
Alex A. Naanou 2020-10-15 03:12:42 +03:00
parent 51fd169d9c
commit 810ccc7c04
3 changed files with 50 additions and 1 deletions

View File

@ -16,6 +16,9 @@
/*********************************************************************/
// Array.prototype.flat polyfill...
//
// NOTE: .flat(..) is not yet supported in IE/Edge...
@ -314,6 +317,49 @@ Array.prototype.toMap = function(normalize){
return m }, new Map()) }
// zip(array, array, ...)
// -> [[item, item, ...], ...]
//
// zip(func, array, array, ...)
// -> [func(i, [item, item, ...]), ...]
//
Array.zip =
function(func, ...arrays){
var i = arrays[0] instanceof Array ?
0
: arrays.shift()
if(func instanceof Array){
arrays.splice(0, 0, func)
func = null }
// build the zip item...
// NOTE: this is done this way to preserve array sparseness...
var s = arrays
.reduce(function(res, a, j){
//a.length > i
i in a
&& (res[j] = a[i])
return res
}, new Array(arrays.length))
return arrays
// check that at least one array is longer than i...
.reduce(function(res, a){
return Math.max(res, i, a.length) }, 0) > i ?
// collect zip item...
[func ? func(i, s) : s]
// get next...
.concat(this.zip(func, i+1, ...arrays))
// done...
: [] }
// XXX would be nice for this to use the instance .zip(..) in recursion...
// ...this might be done by reversign the current implementation, i.e.
// for instance .zip(..) to be the main implementation and for
// Array.zip(..) to be a proxy to that...
Array.prototype.zip =
function(func, ...arrays){
return func instanceof Array ?
this.constructor.zip(this, func, ...arrays)
: this.constructor.zip(func, this, ...arrays) }
/**********************************************************************

View File

@ -25,6 +25,7 @@ A library of JavaScript type extensions, types and type utilities.
- [`<array>.inplaceSortAs(..)`](#arrayinplacesortas)
- [`<array>.toKeys(..)`](#arraytokeys)
- [`<array>.toMap(..)`](#arraytomap)
- [`Array.zip(..)` / `<array>.zip(..)`](#arrayzip--arrayzip)
- [Large `Array` iteration (chunked)](#large-array-iteration-chunked)
- [`<array>.CHUNK_SIZE`](#arraychunk_size)
- [`<array>.mapChunks(..)`](#arraymapchunks)
@ -323,6 +324,8 @@ This will return `true` if:
#### `<array>.toMap(..)`
#### `Array.zip(..)` / `<array>.zip(..)`
### Large `Array` iteration (chunked)

View File

@ -1,6 +1,6 @@
{
"name": "ig-types",
"version": "2.0.16",
"version": "2.0.19",
"description": "Generic JavaScript types and type extensions...",
"main": "main.js",
"scripts": {