Skip to content

Instantly share code, notes, and snippets.

@AlexKott
Created March 10, 2017 11:56
Show Gist options
  • Save AlexKott/992272b71f48186d1710f64d36476c05 to your computer and use it in GitHub Desktop.
Save AlexKott/992272b71f48186d1710f64d36476c05 to your computer and use it in GitHub Desktop.
Flattens an array of type [1, 2, [3, [4]]] to [1, 2, 3, 4].
/**
Simple (Node.js) CLI for the flatten array function.
**/
const flattenArray = require('./flatten-array');
const colors = {
reset: '\033[0m',
pink: '\033[35m',
red: '\033[31m',
green: '\033[32m'
};
const welcomeMsg = `Please enter an ${colors.pink}array${colors.reset} of ${colors.pink}integers${colors.reset}. Type ${colors.red}exit${colors.reset} to end the program.`;
const errorMsg = `${colors.red}Your input is not a JSON array.${colors.reset}`;
function parseInput(data) {
try {
const parsedData = JSON.parse(data);
if (!Array.isArray(parsedData)) {
throw new Error();
} else {
const flatArray = flattenArray(parsedData);
console.log('Your flat array is', colors.green, flatArray, colors.reset);
}
} catch(parseError) {
console.log(errorMsg);
}
}
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (data) => {
if (data.trim() === 'exit') {
process.exit();
} else {
parseInput(data);
}
});
console.log(welcomeMsg);
/**
Tests for the flatten array function.
**/
const assert = require('assert');
const flattenArray = require('./flatten-array');
const colors = {
reset: '\033[0m',
red: '\033[31m',
green: '\033[32m'
};
const flattenArrayTests = [
function it_should_return_an_array() {
const input = [1, 2, 3];
const result = flattenArray(input);
const isArray = Array.isArray(result);
assert(isArray, 'Return value is not an array.');
},
function it_returns_the_same_array_if_array_is_flat() {
const input = [2, 3, 4];
const result = flattenArray(input);
const isSameArray = result.every((el, i) => el === input[i]);
assert(isSameArray, 'Doesn\'t return the same array if it is already flat.');
},
function it_should_flatten_simple_nestings() {
const input = [3, 4, [5, 6]];
const result = flattenArray(input);
const expected = [3, 4, 5, 6];
const isResultCorrect = result.every((el, i) => el === expected[i]);
assert(isResultCorrect, 'Doesn\'t flatten simple nestings.');
},
function it_should_flatten_deeper_nestings() {
const input = [4, 5, [[6], 7, [8, [9], 10, [11, [12]]]]];
const result = flattenArray(input);
const expected = [4, 5, 6, 7, 8, 9, 10, 11, 12];
const isResultCorrect = result.every((el, i) => el === expected[i]);
assert(isResultCorrect, 'Doesn\'t flatten deeper nestings.');
}
];
let failingTests = 0;
flattenArrayTests.forEach(test => {
try {
test();
} catch (assertionError) {
failingTests++;
console.log(`Test failed: ${assertionError.message}`);
}
});
if (failingTests === 0) {
console.log(`${colors.green}All tests passed.${colors.reset}`);
} else if (failingTests === 1) {
console.log(`There was ${colors.red}${failingTests}${colors.reset} failing test.`);
} else {
console.log(`There were ${colors.red}${failingTests}${colors.reset} failing tests.`);
}
/**
Flattens an array of type [1, 2, [3, [4]]] to [1, 2, 3, 4].
**/
module.exports = function flattenArray(arr) {
let isArrayFlat = false,
flatArray = arr,
subArrayIndex;
while (!isArrayFlat) {
flatArray = flatArray.reduce((a, b) => a.concat(b), []);
// If there are still sub arrays, the array needs to be further reduced.
subArrayIndex = flatArray.findIndex(element => Array.isArray(element))
isArrayFlat = subArrayIndex === -1;
}
return flatArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment