Skip to content

Instantly share code, notes, and snippets.

@ever-dev
Created January 27, 2020 22:49
Show Gist options
  • Save ever-dev/e749e4ed746b56818e451f06cb7fffd2 to your computer and use it in GitHub Desktop.
Save ever-dev/e749e4ed746b56818e451f06cb7fffd2 to your computer and use it in GitHub Desktop.
Flatten Numerical Array & unit testing
// flatten the array of integers
const flatten = array =>
JSON.stringify(array) // JSON encode the array to make string
.match(/\d+/g) // extract numbers using regex
.map(x => parseInt(x)); // convert string to numbers
// unit testing with Mocha
var assert = require('assert');
describe('flatten', function() {
it('should flat array of integers', function() {
const input = [1, [2, 34], 5, 6, [7, 8, 9], 10];
const expectedOutput = [1, 2, 34, 5, 6, 7, 8, 9, 10];
const output = flatten(input);
assert.equal(JSON.stringify(output), JSON.stringify(expectedOutput));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment