Skip to content

Instantly share code, notes, and snippets.

@danielfoxp2
Last active July 18, 2018 22:24
Show Gist options
  • Save danielfoxp2/12f916e4c008463500344df3da972364 to your computer and use it in GitHub Desktop.
Save danielfoxp2/12f916e4c008463500344df3da972364 to your computer and use it in GitHub Desktop.
Example to flat an nested array of integers in Javascript, using Jasmine.js as spec suite
class FlatAnything {
flattenThis(collection){
if(itIsNotAnArrayAt(collection)) throw new Error('Only collections are allowed');
if(isAnEmpty(collection)) return [];
const headOfCollection = headOf(collection);
const tailOfCollection = tailOf(collection);
if(itIsNotAnArrayAt(headOfCollection)) return theConcatenationOf([headOfCollection], this.flattenThis(tailOfCollection));
return theConcatenationOf(this.flattenThis(headOfCollection), this.flattenThis(tailOfCollection));
}
}
const headOf = ([head]) => head;
const tailOf = ([, ...tail]) => tail;
const isAnEmpty = (collection) => headOf(collection) === undefined && tailOf(collection).length == false;
const itIsNotAnArrayAt = (thisElement) => Array.isArray(thisElement) == false;
const theConcatenationOf = (thisElement, withThisElement) => thisElement.concat(withThisElement);
module.exports = FlatAnything;
describe('Flat Anything', function(){
var FlatAnything = require('../../../web/static/assets/js/flat_anything');
var flatAnything;
beforeEach(function(){
flatAnything = new FlatAnything();
});
it('should not allow to receive anything but a collection', function() {
expect(() => flatAnything.flattenThis(1)).toThrow(new Error("Only collections are allowed"));
});
it('should transform [x] into [x]', function(){
expect(flatAnything.flattenThis([1])).toEqual([1]);
});
it('should transform [x, y, z] into [x, y, z]', function(){
expect(flatAnything.flattenThis([1, 2, 3])).toEqual([1, 2, 3]);
});
it('should transform [[x]] into [x]', function(){
var array = Array.from([[8,9]]);
expect(flatAnything.flattenThis(array)).toEqual([8,9]);
});
it('should transform [[x], y] into [x, y]', function(){
var array = [[1], 2];
expect(flatAnything.flattenThis(array)).toEqual([1,2]);
});
it('should transform [[x], [y]] into [x, y]', function(){
const array = [[1], [2]];
expect(flatAnything.flattenThis(array)).toEqual([1,2]);
});
it('should transform [[[x]], [y]] into [x, y]', function(){
const array = [[[1]], [2]];
expect(flatAnything.flattenThis(array)).toEqual([1,2]);
});
it('should transform [[w, x,[y]], z] into [w, x, y, z] (Citrusbyte example)', function(){
const array = [[1,2,[3]], 4];
expect(flatAnything.flattenThis(array)).toEqual([1,2,3,4]);
});
it('should transform [[[w, [x, y]]], [z]] into [w, x, y, z]', function(){
const array = [[[1,[2,3]]], [4]];
expect(flatAnything.flattenThis(array)).toEqual([1,2,3,4]);
}); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment