Skip to content

Instantly share code, notes, and snippets.

@kylewelsby
Last active November 5, 2018 11:15
Show Gist options
  • Save kylewelsby/74fa92b0310e5693a9858951aae8ec09 to your computer and use it in GitHub Desktop.
Save kylewelsby/74fa92b0310e5693a9858951aae8ec09 to your computer and use it in GitHub Desktop.
Super simple polyfill for Array#flat
/** Super simple Polyfill for Array#flat
* @experimental
* @interface
* Supports ie9+, chromeAll, firefox4+, safari5+, opera10.5+
* Add https://github.com/es-shims/es5-shim to your project to support older browsers
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
*/
/**
* flattens array
* @function flatten
* @private
* @param {any} arg - the input to flatten if it is an array
* @returns {Array} - Flattend array.
*/
function flatten (arg) {
return arg.reduce(function (accumulator, currentValue) {
return accumulator.concat(
Array.isArray(currentValue) ? flatten(currentValue) : currentValue
)
}, [])
}
/**
* @function flat
* @returns {Array} - flattened array
*/
if (!Array.prototype.hasOwnProperty('flat')) {
/* eslint-disable no-extend-native */
Object.defineProperty(Array.prototype, 'flat', {
value: function () {
return flatten(this)
}
})
/* eslint-enable no-extend-native */
}
function flatten(t){return t.reduce(function(t,r){return t.concat(Array.isArray(r)?flatten(r):r)},[])}Array.prototype.hasOwnProperty("flat")||Object.defineProperty(Array.prototype,"flat",{value:function(){return flatten(this)}});
/* globals describe,it,expect */
/* To test, run jest */
require('./array-flatten')
describe('Array#flatten', () => {
it('flattens array', () => {
let input = [[1, 2, [3]], 4]
expect(input.flat()).toEqual([1, 2, 3, 4])
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment