Skip to content

Instantly share code, notes, and snippets.

@bbagdad
Created April 26, 2018 08:55
Show Gist options
  • Save bbagdad/927e1b494a5157f0bf37afb928413a5b to your computer and use it in GitHub Desktop.
Save bbagdad/927e1b494a5157f0bf37afb928413a5b 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.
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