Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Theorem application test for Experienced Backend Engineer
/*
* Copyright (c) 2019 <CompanyName>
* All rights reserved.
*/
'use strict';
function flattenArray(sourceArray) {
var resultArray = [];
for (var item of sourceArray) {
if (Array.isArray(item)) {
resultArray = resultArray.concat(flattenArray(item));
} else {
resultArray.push(item);
}
}
return resultArray;
}
module.exports = flattenArray;
{
"name": "flatten-array",
"version": "1.0.0",
"description": "",
"main": "flatten-array.js",
"scripts": {
"test": "mocha"
},
"author": "Rosberg Linhares",
"license": "MIT",
"devDependencies": {
"mocha": "^6.1.4"
}
}
/*
* Copyright (c) 2019 <CompanyName>
* All rights reserved.
*/
'use strict';
const assert = require('assert');
const flattenArray = require('../flatten-array.js');
describe('#flattenArray()', function() {
it('Empty array', function() {
var resultArray = flattenArray([]);
assert.deepEqual(resultArray, []);
});
it('Nested empty arrays', function() {
var resultArray = flattenArray([ [ ], [ [ ], [ ], [ [ ] ] ] ]);
assert.deepEqual(resultArray, []);
});
it('Nested empty arrays with single item', function() {
var resultArray = flattenArray([ [ ], [ [ ], [ ], [ 5, [ ] ] ] ]);
assert.deepEqual(resultArray, [ 5 ]);
});
it('Single items', function() {
var resultArray = flattenArray([ 5, 7, 1, 3 ]);
assert.deepEqual(resultArray, [ 5, 7, 1, 3 ]);
});
it('Single items as array', function() {
var resultArray = flattenArray([ [ 5 ], [ 7 ], [ 1 ], [ 3 ] ]);
assert.deepEqual(resultArray, [ 5, 7, 1, 3 ]);
});
it('Deep level single item', function() {
var resultArray = flattenArray([ [ [ [ [ 8 ] ] ] ] ]);
assert.deepEqual(resultArray, [ 8 ]);
});
it('Deep level mixed', function() {
var resultArray = flattenArray([ [ [ [ 7 ], [ 4, 5, 6 ], [ ], ], 8, 9 ], 1, [ 2, 3, [ 4 ] ] ]);
assert.deepEqual(resultArray, [ 7, 4, 5, 6, 8, 9, 1, 2, 3, 4 ]);
});
it('Theorem test', function() {
var resultArray = flattenArray([ [ 1, 2, [ 3 ] ], 4 ]);
assert.deepEqual(resultArray, [ 1, 2, 3, 4 ]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment