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

    When using recursion, you must be mindful of the dreaded infinite loop. Using the recursive function that we’ve built up over the previous lessons, we look at how a simple duplicated configuration item could cause chaos for our program as it has no context of which items it has previously seen. We fix this problem by introducing a parents array, which can keep track of which top-level commands have already been accessed.

    Previous:

    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);

    ----------

    Code:

    let input, config;
    
    input = ['dist'];
    
    config = {
      "dist": ["build", "deploy"],
      "build": ['js', 'css', 'vender', 'dist'],
      "js": ['babel', 'ng-Annotate', "uglify"],
      "css": ["sass", "css-min"]
    };
    
    var res = getTasks(config, input);
    
    function getTasks(config, input, initial, parent){
      
      initial = initial || [];
      parent = parent || [];
      
      return input.reduce((prev, next)=>{
        
        if(parent.indexOf(next) > -1){
    console.log('infinite loop detected!');
    return prev; } if(config[next]){ return getTasks(config ,config[next], prev, parent.concat(next)); }else{ return prev.concat(next); } }, initial); }; console.log(res);
  • 相关阅读:
    Java_JAVA6动态编译的问题
    Java_动态加载类(英文)
    Java_Java Compiler 应用实例
    Java_关于App class loader的总结
    Java_动态加载
    Java_Java SE6调用动态编译
    python捕获Ctrl+C信号
    python使用协程并发
    python使用多进程
    python使用多线程
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5087602.html
Copyright © 2011-2022 走看看