Skip to content

Instantly share code, notes, and snippets.

@brendanmoore
Created September 30, 2020 10:12
Show Gist options
  • Save brendanmoore/001992b3948b1b8f11a38716c00fb134 to your computer and use it in GitHub Desktop.
Save brendanmoore/001992b3948b1b8f11a38716c00fb134 to your computer and use it in GitHub Desktop.
if (!Array.prototype.flat) {
Object.defineProperty(Array.prototype, 'flat', {
configurable: true,
value: function flat () {
var depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]);
return depth ? Array.prototype.reduce.call(this, function (acc, cur) {
if (Array.isArray(cur)) {
acc.push.apply(acc, flat.call(cur, depth - 1));
} else {
acc.push(cur);
}
return acc;
}, []) : Array.prototype.slice.call(this);
},
writable: true
});
}
if (!Array.prototype.flatMap) {
Object.defineProperty(Array.prototype, 'flatMap', {
configurable: true,
value: function flatMap (callback) {
return Array.prototype.map.apply(this, arguments).flat();
},
writable: true
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment