Skip to content

Instantly share code, notes, and snippets.

@rhom6us
Last active June 24, 2023 20:30
Show Gist options
  • Save rhom6us/4efe133a423bf7fe038e72e23d3152ca to your computer and use it in GitHub Desktop.
Save rhom6us/4efe133a423bf7fe038e72e23d3152ca to your computer and use it in GitHub Desktop.
Array.prototype.toMap
/**
* @param {Function} kvpFn - The function used to create the mapping. Return either the value to be used as key and the entire item will be set as the value, or return a key/value pair in the format [key, value] to specify both explicitely.
* @returns {Map}
*/
Array.prototype.toMap = function (kvpFn){
const input = this.map(kvpFn);
if(!input.every(p => Array.isArray(p) && p.length === 2) {
throw new TypeError('kvpFn must return a two element array tuple');
}
return new Map(input);
}
Array.prototype.toMap2 = function (keySelector, valueSelector = p=>p){
return new Map(this.map(item => [keySelector(item), valueSelector(item)]));
}
neWay;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment