Skip to content

Instantly share code, notes, and snippets.

@ronaldroe

ronaldroe/flatten-test.js

Last active Mar 10, 2020
Embed
What would you like to do?
Array Flatten
// Decided against a testing framework for something so simple.
// This test takes an array, loops through each top level index
// and logs an error if the index contains an array.
// Passes are tallied, and passes/fails are output at the end of the test.
const flattenTest = arr => {
// Define error message and initialize pass counter
const errorMessage = ind => `Index ${ind} contains an array`;
let passCount = 0;
arr.forEach((item, ind) => {
// If the item is an array, log the message
if(Array.isArray(item)){
console.error(errorMessage(ind));
// If not an array, increment pass counter
} else {
passCount++;
}
});
// Log out results
console.log(`${arr.length} total top level indexes.`);
console.log(`${passCount} tests passed.`);
console.log(`${arr.length - passCount} tests failed.`);
}
module.exports = flattenTest;
const flatten = arr => {
let outputArr = [];
// Loop through each index of the array
arr.forEach(item => {
// If the current item is not an array, push its value immediately.
if(!Array.isArray(item)){
outputArr.push(item);
// If the current item is an array, recurse into it.
// It's usually better to not use recursion, but in this case,
// depth is unknown, and recursion makes sense.
} else {
// Spread the results of the recursion into the output array.
outputArr.push(...flatten(item));
}
});
return outputArr;
}
// Created for use with Node or other CommonJS
module.exports = flatten;
// Run this file using `node index.js` to see results.
const flattenTest = require('./flatten-test.js');
const flatten = require('./flatten.js');
const arr = [[1,2,[3]],4];
// First, test flatten function
console.log('Running example array with flatten function');
flattenTest(flatten(arr));
// Second, show test failures using input array
console.log('\nRunning example array without flatten function')
flattenTest(arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.