【发布时间】:2020-11-22 12:48:00
【问题描述】:
我正在尝试为这个问题编写一个功能解决方案。我已经有一个解决方案,它使用循环和突变而不使用递归(我知道我在下面尝试的涉及突变,我试图避免这种情况)。
请在下面的 cmets 中查看预期输出。我要强调的是,元素不一定是唯一的,排序无关紧要。
const getNamesWhichFillHoles = (namesArrayWithHoles, namesArrayFilled, fillers = []) => {
const holey = [...namesArrayWithHoles].filter(Boolean);
const filled = [...namesArrayFilled].filter(Boolean);
const fillerIndexInFilled = filled.findIndex(name => !holey.includes(name));
if (fillerIndexInFilled === -1) return fillers;
const filler = filled[fillerIndexInFilled];
const fillerIndexInHoley = holey.findIndex(name => name == filler);
fillers.push(filler);
filled[fillerIndexInFilled] = null;
holey[fillerIndexInHoley] = null;
return getNamesWhichFillHoles(holey, filled, fillers);
}
const namesArrayWithHoles = ['Bob', null, null, 'Sue', null];
const namesArrayFilled = ['Jim', 'Bob', 'Bob', 'Sam', 'Sue',];
const fillerNames = getNamesWhichFillHoles(namesArrayWithHoles, namesArrayFilled);
console.log(fillerNames); // [ 'Jim', 'Sam' ]
// should be: [ 'Jim', 'Sam', 'Bob' ]
【问题讨论】:
标签: javascript arrays functional-programming purely-functional