Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. 'use strict';
  2. // server.js
  3. // load the things we need
  4. //This is to parse the arguments from the cmd line
  5. const optimist = require('optimist');
  6.  
  7. //listen for our initial argument.
  8. const abArray = optimist.argv["array"];
  9. let insideArray = [1,2,3,[1,2,[4,5],3,4],2];
  10. let passedInput = true;
  11.  
  12. const app = {
  13.  
  14. //main function
  15. runThisThing: function (arrayInput){
  16. const arrayToFlatten = this.sanitizeInput(arrayInput);
  17. const result = this.flattenArray(arrayToFlatten);
  18.  
  19. if (!passedInput){
  20. console.log("You need to pass the array to flatten as an argument: --array arrayToFlatten");
  21. }
  22.  
  23. console.log(result);
  24. },
  25.  
  26. sanitizeInput: function(arg){
  27. //Check to see if user passed any arguments
  28. if (arg && arg.length > 0){
  29. //Because the intial argument from optimist is always a string, we gast
  30. //convert to an array.
  31. try {
  32. insideArray = JSON.parse(arg);
  33. } catch (e) {
  34. console.log("Sorry, this is likely an invalid array object " + e);
  35. insideArray = [];
  36. }
  37. } else {
  38. passedInput = false
  39. }
  40.  
  41. return insideArray;
  42. },
  43.  
  44. flattenArray: function(abArray){
  45. //Check to see if the parsed value is a valid array still.
  46. let finalValue = []
  47. if (Array.isArray(insideArray)){
  48. //do the actual flattening, then add "[]" to end and front of the resulting string
  49. //to make the parsing back to an array complete
  50. const result = "[" + insideArray.toString() + "]";
  51. finalValue = JSON.parse(result);
  52. }
  53.  
  54. return finalValue;
  55. }
  56.  
  57. }
  58.  
  59. app.runThisThing(abArray);
  60.  
  61. module.exports = app;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement