2 回答
TA贡献1821条经验 获得超4个赞
我实际上会采用与您类似的方法,使用 achunk作为临时值来存储不完整的组。
const group = (data = [], chunk = [], res = []) => {
if (!data.length) {
// input is empty,
// flush any possible incomplete chunk
// and return result
return [...res, ...chunk];
}
const [head, ...tail] = data;
const next = (...xs) => group(tail, ...xs);
if (head.option) {
// head.option is true, so you can
// safely put it in tail position
return next(chunk, [...res, head]);
}
if (chunk.length < 4) {
// chunk is not-complete, so keep accumulating
return next([...chunk, head], res);
}
// chunk is complete, append it to the rest
// and create a new one with the current value
return next([head], [...res, ...chunk]);
};
const data = [
{name: 'a', option: false},
{name: 'b', option: false},
{name: 'c', option: false},
{name: 'd', option: false},
{name: 'e', option: false},
{name: 'f', option: true},
{name: 'g', option: true},
{name: 'h', option: false},
{name: 'i', option: true},
{name: 'j', option: false},
{name: 'k', option: false},
];
console.log('result is', group(data));
递归在这里是可取的,它们的状态是
空输入(基本情况)
chunk, (res + head)
(chunk + head), res
head, (res + chunk)
TA贡献1876条经验 获得超5个赞
你可以使用递归。
const bubble = (xxs, acc = []) => {
if (xxs.length === 0) return acc;
if (acc.length === 4) return [...acc, ...bubble(xxs)];
const [x, ...xs] = xxs;
if (x.option) return [x, ...bubble(xs, acc)];
return bubble(xs, [...acc, x]);
};
const nums = [
{name: 'a', option: false},
{name: 'b', option: false},
{name: 'c', option: false},
{name: 'd', option: false},
{name: 'e', option: false},
{name: 'f', option: true},
{name: 'g', option: true},
{name: 'h', option: false},
{name: 'i', option: true},
{name: 'j', option: false},
{name: 'k', option: false},
];
const result = bubble(nums);
console.log(result);
它效率不高,但很实用。
添加回答
举报