Created
July 4, 2019 14:11
-
-
Save knightbenax/db2360fb8119131bf2a1339941c5c185 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// server.js | |
// load the things we need | |
//This is to parse the arguments from the cmd line | |
const optimist = require('optimist'); | |
//listen for our initial argument. | |
const abArray = optimist.argv["array"]; | |
let insideArray = [1,2,3,[1,2,[4,5],3,4],2]; | |
let passedInput = true; | |
const app = { | |
//main function | |
runThisThing: function (arrayInput){ | |
const arrayToFlatten = this.sanitizeInput(arrayInput); | |
const result = this.flattenArray(arrayToFlatten); | |
if (!passedInput){ | |
console.log("You need to pass the array to flatten as an argument: --array arrayToFlatten"); | |
} | |
console.log(result); | |
}, | |
sanitizeInput: function(arg){ | |
//Check to see if user passed any arguments | |
if (arg && arg.length > 0){ | |
//Because the intial argument from optimist is always a string, we gast | |
//convert to an array. | |
try { | |
insideArray = JSON.parse(arg); | |
} catch (e) { | |
console.log("Sorry, this is likely an invalid array object " + e); | |
insideArray = []; | |
} | |
} else { | |
passedInput = false | |
} | |
return insideArray; | |
}, | |
flattenArray: function(abArray){ | |
//Check to see if the parsed value is a valid array still. | |
let finalValue = [] | |
if (Array.isArray(insideArray)){ | |
//do the actual flattening, then add "[]" to end and front of the resulting string | |
//to make the parsing back to an array complete | |
const result = "[" + insideArray.toString() + "]"; | |
finalValue = JSON.parse(result); | |
} | |
return finalValue; | |
} | |
} | |
app.runThisThing(abArray); | |
module.exports = app; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// load the things we need | |
var expect = require('chai').expect; | |
const app = require("../server.js"); | |
describe('Run Things', function () { | |
it('This should return a valid array', function () { | |
const values = "[2, 4]"; | |
const result = app.sanitizeInput(values); | |
expect(Array.isArray(result)).to.be.equal(true); | |
}); | |
it('This should return a valid array', function () { | |
const values = "[2, 4]"; | |
const result = app.flattenArray(values); | |
expect(Array.isArray(result)).to.be.equal(true); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment