javascript - How to implement nested methods with specified depth in js
PHP中文网
PHP中文网 2017-05-19 10:43:39
0
3
463

I met an interview question today. I found a problem when using js to implement the algorithm. How to use js to implement such a method. Given a function and nesting depth (int type), return a nested structure as shown below?

Given parameters: fn, deepLength

Return structure (take deepLength=3 as an example):

  for (var x = 0; x <= 9; x++) {
    for (var y = 0; y <= 9; y++) {
      for (var z = 0; z <= 9; z++) {
        rs = fn([x,y,z])
      }
    }
  }

After thinking about it for a while, it seems that it can only be achieved through nested functions. Is there a more elegant implementation method?


I summarized everyone’s methods and put them on a demo page for your reference

Attached link Interview question: Dividing cookies

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
大家讲道理
function loop(fn, n, args = []) {
  if (n === 0) {
    fn.apply(null, args);
    return;
  }

  for (let i = 0; i <= 9; i++) {
    loop(fn, n - 1, args.concat(i));
  }
}


loop((...args) => {
  console.log(args);
}, 3);
仅有的幸福

Implemented by building strings, but it feels too inelegant. .

var deep = (fn, deeplen) =>{
  var rs = null;
  var args = [];
  var content = 'var trueArgs = [];for(var i =0;i<args.length;i++){trueArgs[i]=eval(args[i])}rs = fn(trueArgs);';
  for (var i = 0; i < deeplen; i++) {
    args.push(`iter${i}`);
    content = `for ( var iter${i} = 0; iter${i}<=9; iter${i}++){ ${content} }`;
  }
  new Function('fn', 'args', content)(fn, args);
  return rs;
}

Interview question reference code

大家讲道理
let loop = (fn, layer) => {
    return (arr) => {
        for (let i = 0; i <= 9; i++) {
            arr[layer] = i
            fn(arr)
        }
    }
}
let nestedLoop = (fn, deepLength) => {
    for (let i = deepLength; i > 0; i--) {
        fn = loop(fn, i - 1)
    }
    fn ([])
}

nestedLoop((arr) => console.log(arr.join('')), 3)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template