Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '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;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement