Skip to content

Instantly share code, notes, and snippets.

@developit
Last active April 11, 2020 23:59
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developit/50364079cf0390a73e745e513fa912d9 to your computer and use it in GitHub Desktop.
Save developit/50364079cf0390a73e745e513fa912d9 to your computer and use it in GitHub Desktop.
140b polyfill for Array.prototype.flat() and Array.prototype.flatMap(). https://npm.im/tiny-array-flat-polyfill

140b polyfill for [].flat() & [].flatMap()

Install: npm i tiny-array-flat-polyfill

Usage:

import 'tiny-array-flat-polyfill';

const ARR = [1, [2, [3]], [[[4]]], 5]

ARR.flat() // [1, 2, [3], [[4]], 5]

ARR.flat(4) // [1, 2, 3, 4, 5]

[[1,2],[3,4]].flatMap(([x,y])=>x+y) // [3,7]

Changelog

  • 0.2.1: fix handling of .flat(Infinity)
  • 0.2.0: only polyfill if .flat() is not already available
  • 0.1.0: initial release

See tests

{
"name": "tiny-array-flat-polyfill",
"description": "140b polyfill for Array.prototype.flat() and Array.prototype.flatMap()",
"version": "0.2.1",
"author": "Jason Miller <jason@developit.ca>",
"main": "tiny-array-flat-polyfill.min.js",
"repository": "gist:50364079cf0",
"homepage": "https://gist.github.com/50364079cf0390a73e745e513fa912d9",
"scripts": { "prepack": "mv *tiny-array-flat-polyfill.md README.md", "postpack": "mv README.md *tiny-array-flat-polyfill.md" },
"license": "Apache-2.0"
}
if (!Array.prototype.flat) {
Array.prototype.flat = function flat(d,c) {
return c=this.concat.apply([],this),
d>1 && c.some(Array.isArray) ? c.flat(d-1) : c;
};
Array.prototype.flatMap = function(c,a) {
return this.map(c,a).flat();
};
}
Array.prototype.flat||(Array.prototype.flat=function(t,r){return r=this.concat.apply([],this),t>1&&r.some(Array.isArray)?r.flat(t-1):r},Array.prototype.flatMap=function(t,r){return this.map(t,r).flat()})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment