Created
January 16, 2019 13:07
-
-
Save ycmjason/6250b0af62f52a09d5bceb4080968a69 to your computer and use it in GitHub Desktop.
Array.prototype.flatMap ponyfill
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
const flatMap = (xs, fn, thisArg) => { | |
if (typeof Array.prototype.flatMap === 'function') { | |
return Array.prototype.flatMap.call(xs, fn, thisArg); | |
} | |
const bFn = fn.bind(thisArg); | |
return xs.reduce((acc, x) => { | |
const r = bFn(x); | |
if (Array.isArray(r)) return [...acc, ...r]; | |
return [...acc, r]; | |
}, []); | |
}; | |
// Usage | |
flatMap([1,2,3], x => [x, x, x]); // [ 1, 1, 1, 2, 2, 2, 3, 3, 3 ] | |
flatMap([1,2,3], x => x); // [ 1, 2, 3 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment