首页 > 编程语言 > 详细

[Javascript] Intro to Recursion - Refactoring to a Pure Function

时间:2015-12-18 06:53:13      阅读:305      评论:0      收藏:0      [点我收藏+]

Previous post: http://www.cnblogs.com/Answer1215/p/4990418.html

 

let input, config, tasks;

input = [‘dist‘];

config = {
  "dist": ["build", "deploy"],
  "build": [‘js‘, ‘css‘, ‘vender‘],
  "js": [‘babel‘, ‘ng-Annotate‘, "uglify"],
  "css": ["sass", "css-min"]
};

tasks = [];

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 has some problem:

  • we depend on the outside variable ‘tasks‘ and ‘config‘, so there are 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 = [];

var res = getTasks(input, []);

function getTasks(input, initial){
  
  return input.reduce((prev, next)=>{
    if(config[next]){
      return getTasks(config[next], prev);
    }else{
      return prev.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 is 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"]
};

var res = getTasks(config, input, []);

function getTasks(config, input, initial){
  
  return input.reduce((prev, next)=>{
    if(config[next]){
      return getTasks(config ,config[next], prev);
    }else{
      return prev.concat(next);
    }
  }, initial);
};

console.log(res);

 

[Javascript] Intro to Recursion - Refactoring to a Pure Function

原文:http://www.cnblogs.com/Answer1215/p/5055914.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!