zoukankan      html  css  js  c++  java
  • [Javascript] Intro to Recursion

    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);
  • 相关阅读:
    【Jmeter】 jmeter-server.bat 无法启动
    Jmeter场景设置与监听
    Jmeter性能测试配置
    【VMware】“该虚拟机似乎正在使用中”
    Jmeter介绍以及脚本制作与调试
    性能测试简介
    robotframework配置邮箱服务器
    Java冒泡排序
    LN(A)MT单机版架构部署
    Openstack之八:部署自服务网络
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5055914.html
Copyright © 2011-2022 走看看