deanmono
10/10/2019 - 10:13 PM

Theorem Flattener

Theorem Flattener

Take a nested array and crush it into a puny little baby array, unremorsefully

Installation

npm install to build the module

System Dependencies

Install the application's dependencies.

  1. Node.js, NPM
  2. Uglifyjs
  3. Jasmine

Running Jasmin Test

Jasmine testing can be ran using npm test

Code Example

let items = [[1,2,[3]],4];

flattener.flatten(items);

// [1,2,3,4]
/*!
 * UMD style Module
 */
//
(function (root, factory) {
    // Support CommonJS, AMD, and UMD modularization
    if ( typeof define === 'function' && define.amd ) {
        define([], function () {
            return factory(root);
        });
    } else if ( typeof exports === 'object' ) {
        module.exports = factory(root);
    } else {
        root.theorem = factory(root);
    }
})(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, function (window) {

    'use strict';

    /**
     *  Recursively find only integers from stack and move to flat array
     *  @params {array} the nested array to flatten
     *  @return {array} flat array of integers
     */
     function flatten(items) {

        const flat = [];

        items.forEach(item => {
            if (Array.isArray(item)) {
                flat.push(...flatten(item));
            } else if(Number.isInteger(item)) {
                flat.push(item);
            }
        });

        return flat;
    };

    return {
        flatten: flatten
    }
});
{
  "name": "theorem-flattener",
  "version": "1.0.0",
  "description": "Take a nested array and crush it into a puny little baby array unremorsefully",
  "main": "index.js",
  "scripts": {
    "install": "uglifyjs --self -c -m -o theorem-flattener.js",
    "test": "jasmine theorem-flattener.spec.js"
  },
  "author": "Dean Monistere",
  "license": "MIT",
  "devDependencies": {
    "jasmine": "^3.5.0",
    "uglify-js": "^3.6.1"
  }
}
describe("Flattener", function() {
    let Flattener = require('./index.js');
    let flattener;

    let nest = [[1,2,[3]],4];

    beforeEach(function() {
        flattener = Flattener;
    });

    it("should be able to flatten", function() {
        expect(flattener.flatten(nest)).toEqual([1,2,3,4]);
    });
});