Skip to content

Instantly share code, notes, and snippets.

@ycmjason ycmjason/flatMap.js
Created Jan 16, 2019

Embed
What would you like to do?
Array.prototype.flatMap ponyfill
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
You can’t perform that action at this time.