Created
January 6, 2015 22:29
-
-
Save JonathanGawrych/e9f5e401fecd1a86527c to your computer and use it in GitHub Desktop.
Bullet-proof function to transform an array into a map using a callback function to determine the key
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
| // Similar to Array.prototype.map, this function takes an array-like object and turns it into an associative map | |
| // Instead of the callback function being used to transform the value in the returned array, it is called to get | |
| // the key instead. Unlike map, this function will use the second param in place of `this`, if `this` isn't bound | |
| function mapAssociative(callback, thisArg) { | |
| var arr, len; | |
| /*jshint validthis:true */ | |
| arr = this || thisArg; | |
| /*jshint validthis:false */ | |
| if (arr === window) { | |
| arr = thisArg; | |
| } | |
| if (arr == null || !(length in arr)) { | |
| throw new TypeError(' this is not an array or array-like'); | |
| } | |
| if (typeof callback !== 'function') { | |
| throw new TypeError(callback + ' is not a function'); | |
| } | |
| arr = Object(arr); // transform to object | |
| len = arr.length >>> 0; // transform to uint32 | |
| var obj = {}; | |
| for (var i = 0; i < len; i++) { | |
| if (i in arr) { | |
| obj[callback.call(thisArg, arr[i], i, arr)] = arr[i]; | |
| } | |
| } | |
| return obj; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment