Last active
June 24, 2023 20:30
-
-
Save rhom6us/4efe133a423bf7fe038e72e23d3152ca to your computer and use it in GitHub Desktop.
Array.prototype.toMap
This file contains 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
/** | |
* @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