Skip to content

Instantly share code, notes, and snippets.

@getify
Last active August 17, 2017 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/03ecf0aa5b4fb49f156040eac62b92df to your computer and use it in GitHub Desktop.
Save getify/03ecf0aa5b4fb49f156040eac62b92df to your computer and use it in GitHub Desktop.
mapZip(..): kinda like the inverse of flatMap(..) I guess
var list = [1,2,3,4,5];
zip( list, map( x => x ** 2, list ) );
// [[1,1],[2,4],[3,9],[4,16],[5,25]]
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
Copy link

phambaonam commented Aug 17, 2017

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.

@getify
Copy link
Author

getify commented Aug 17, 2017

@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