Created
January 30, 2019 15:35
-
-
Save ksafranski/e7c6165c333b17c1cf9f055edc4b778e to your computer and use it in GitHub Desktop.
Revisions
-
ksafranski created this gist
Jan 30, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,17 @@ /** * Function for converting arbitrarily nested arrays into a single, flat array * @param {Array} arr * @returns {Array} */ function flatDeep (arr) { if (!Array.isArray(arr)) throw new Error('Expected type `Array`') return arr.reduce((acc, el) => acc.concat(Array.isArray(el) ? flatDeep(el) : el), []) } // Tests const assert = require('assert') assert.throws(() => flatDeep('foo'), Error) assert.deepEqual(flatDeep([[1,2,[3]],4]), [1, 2, 3, 4]) assert.deepEqual(flatDeep([1,,3,[4]]), [1,3,4]) assert.deepEqual(flatDeep([1, ['foo', true]]), [1,'foo',true]) assert.deepEqual(flatDeep([[1], [{ foo: 'bar' }]]), [1,{foo: 'bar'}])