Skip to content

Instantly share code, notes, and snippets.

@iykekings
Last active December 17, 2019 16:26
Show Gist options
  • Save iykekings/101feb27a49f49574a490269e5fc0863 to your computer and use it in GitHub Desktop.
Save iykekings/101feb27a49f49574a490269e5fc0863 to your computer and use it in GitHub Desktop.
Implementation of Array flattening with JavaScript

This gist discusses the implementation of Array flattening with JavaScript. It returns a single array with all of its element recursively flattened.

To Run Test

  node flat_array_test.js
const flat = array => {
let collector = [];
if (!(array instanceof Array)) {
throw new Error('Not an array');
}
for (let elem of array) {
if (elem instanceof Array) {
collector = [...collector, ...flat(elem)];
} else {
collector = [...collector, elem];
}
}
return collector;
};
module.exports = flat;
const flat = require('./flat_array');
const { assertDeepEqual, shouldThrow } = require('./test');
assertDeepEqual(
flat([1, 2, 3, [4, 5, [6, 7, 8, [9, 10]]], 11, 12, [13, 14]]),
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
'Should flatten all nested arrays into a single one'
);
assertDeepEqual(
flat([1, 2, 3, [4, 5, [6, 7, 8, [9, 10]]]]),
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'Should flatten all nested arrays into a single one 2'
);
assertDeepEqual(
flat([1, 2, 3]),
[1, 2, 3],
'Should return the same array if it is flattened already'
);
assertDeepEqual(flat([]), [], 'Return an empty array if the input is empty');
assertDeepEqual(flat([1, 2, 3, []]), [1, 2, 3], 'Ignore empty array');
shouldThrow(() => flat(1), 'Should throw an error if input is not an array');
// Simple Test Library
function assertEq(left, right, info = '') {
if (left !== right) {
console.error(`Test Failed ❗️:
Expected => ${right}
Got => ${left}`);
} else {
console.log(`Test: ${info} Passed`);
}
}
function assertDeepEqual(left, right, info = '') {
if (!left.every((e, i) => e === right[i])) {
console.error(`Test Failed:
Expected => ${right}
Got => ${left}\n`);
} else {
console.log(`\n${info}: Passed ✅\n`);
}
}
function shouldThrow(cb, info = '') {
let hasthrown = false;
try {
cb();
} catch (error) {
hasthrown = true;
console.log(`\n${info}: Passed ✅\n`);
} finally {
if (!hasthrown) {
console.error(`Test Failed: Didn't throw an error\n`);
}
}
}
module.exports = { assertEq, assertDeepEqual, shouldThrow };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment