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
大家讲道理2017-05-19 10:45:39
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);
仅有的幸福2017-05-19 10:45:39
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
大家讲道理2017-05-19 10:45:39
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)