Previous post:http://www.cnblogs.com/answer1215/p/4990418.html
= [' dist '= { "dist": ["Build", "deploy"], "Build": [' js ', ' css ', ' vender '], "js": [' Babel ', ' ng-annotate ', "uglify"], "css": ["Sass", "css-min"= []; Gettasks (input); function gettasks (input) { Input.foreach (Task)={ if(Config[task]) { gettasks (Config[task]); } Else { Tasks.push (Task);}} )}; Console.log (tasks);
The Gettasks works but have some problem:
- We depend on the outside variable ' tasks ' and ' config ', so there is side effect
- There is no return value, hard to test
Let input, config, Tasks;input= [' Dist '];config= { "Dist": ["Build", "deploy"], "Build": [' js ', ' css ', ' vender '], "JS": [' Babel ', ' ng-annotate ', ' uglify '], "CSS": ["Sass", "Css-min"]};tasks= [];varres =gettasks (input, []);functiongettasks (input, initial) {returnInput.reduce (prev, next) ={ if(Config[next]) {returnGettasks (Config[next], prev); }Else{ returnPrev.concat (next); }}, initial);}; Console.log (res);
The code has been improved, we return the value from the Gettasks () function and we don ' t modify the tasks array anymore.
Just One thing we still need to do are we still depend on ' config ':
Let input, Config;input= [' Dist '];config= { "Dist": ["Build", "deploy"], "Build": [' js ', ' css ', ' vender '], "JS": [' Babel ', ' ng-annotate ', ' uglify '], "CSS": ["Sass", "Css-min"]};varres =gettasks (config, input, []);functiongettasks (config, input, initial) {returnInput.reduce (prev, next) ={ if(Config[next]) {returngettasks (config, Config[next], prev); }Else{ returnPrev.concat (next); }}, initial);}; Console.log (res);
[Javascript] Intro to Recursion-refactoring to a Pure Function