Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Created January 16, 2019 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ycmjason/6250b0af62f52a09d5bceb4080968a69 to your computer and use it in GitHub Desktop.
Save ycmjason/6250b0af62f52a09d5bceb4080968a69 to your computer and use it in GitHub Desktop.
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