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);
  • 相关阅读:
    一般图最大匹配
    UOJ164 线段树历史最值查询
    一个经典的排列组合面试题目
    动态代理理解
    JAVA nio
    hadoop NameNode 实现分析
    以一个上传文件的例子来说 DistributedFileSystem
    hadoop IPC 源代码分析
    hadoop DataNode实现分析
    HDFS 整体把握
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5087602.html
Copyright © 2011-2022 走看看