Created
April 26, 2018 08:56
-
-
Save bbagdad/212e1c6aa7bdf3ea56267bf03f745c9e to your computer and use it in GitHub Desktop.
JavaScript manMany, Projects each element of a sequence to an Array and flattens the resulting sequences into one sequence.
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
// Projects each element of a sequence to an Array and flattens the resulting sequences into one sequence. | |
if (!Array.prototype.mapMany) { | |
Object.defineProperty(Array.prototype, 'mapMany', { | |
value: function (callback) { | |
if (this === null) { | |
throw new TypeError('Array.prototype.mapMany ' + | |
'called on null or undefined'); | |
} | |
if (typeof callback !== 'function') { | |
throw new TypeError(callback + | |
' is not a function'); | |
} | |
// 1. Let O be ? ToObject(this value). | |
var o = Object(this); | |
// 2. Let len be ? ToLength(? Get(O, "length")). | |
var len = o.length >>> 0; | |
// Steps 3, 4, 5, 6, 7 | |
var k = 0; | |
// Start with empty array | |
var value = []; | |
// 8. Repeat, while k < len | |
while (k < len) { | |
// if k exists in o | |
if (k in o) { | |
value = value.concat(callback(o[k], k, o)) | |
} | |
// d. Increase k by 1. | |
k++; | |
} | |
// 9. Return accumulator. | |
return value; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage Example:
Result: