-
-
Save getify/03ecf0aa5b4fb49f156040eac62b92df to your computer and use it in GitHub Desktop.
mapZip(..): kinda like the inverse of flatMap(..) I guess
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var list = [1,2,3,4,5]; | |
zip( list, map( x => x ** 2, list ) ); | |
// [[1,1],[2,4],[3,9],[4,16],[5,25]] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mapZip(mapper,list) { | |
return map( x => [x,mapper(x)], list ); | |
} | |
var list = [1,2,3,4,5]; | |
mapZip( x => x ** 2, list ); | |
// [[1,1],[2,4],[3,9],[4,16],[5,25]] |
@phambaonam yes, this is assuming map(..)
(and zip(..)
) utilities present, generally provided by an FP lib.
Here's some basic implementations of those functions if you're curious:
function map(mapperFn,arr) {
var newList = [];
for (let idx = 0; idx < arr.length; idx++) {
newList.push(
mapperFn( arr[idx], idx, arr )
);
}
return newList;
}
function zip(arr1,arr2) {
var zipped = [];
arr1 = arr1.slice();
arr2 = arr2.slice();
while (arr1.length > 0 && arr2.length > 0) {
zipped.push( [ arr1.shift(), arr2.shift() ] );
}
return zipped;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, when i run this code on my IDE . I see error as
ReferenceError: zip is not defined, map is not defined
. So must i write core function for zip and map function? Thanks.