我有两个不同长度的列表
var parents = [
{ name: "foo", check: true },
{ name: "foo", check: true },
{ name: "bar", check: false }
];
var children = [
{ name: "foo", check: false, override: false },
{ name: "foo", check: false, override: false }
];
这些列表与此规则相关:(密钥是用户名)
代码
function applyLogic(parents, children) {
for(let i = 0; i < children.length; i++) {
var child = children[i];
var sameUsername = parents
.filter((x) => x.username === child.username);
if(sameUsername.length === 0) {
continue;
}
for(let j = 0; j < sameUsername.length; j++) {
if(j > 0 || sameUsername.length == children.filter((x) => x.username == child.username).length) {
children.splice(++i, 0, child);
}
}
}
}
码
function applyLogic(parents, children) {
for (let i = 0; i < children.length; i++) {
var child = children[i];
var sameUsername = parents.filter((x) => x.username === child.username);
if (sameUsername.length === 0) {
continue;
}
for (let j = 0; j < sameUsername.length; j++) {
if (j > 0 || sameUsername.length == children.filter((x) => x.username == child.username).length) {
let newItem = {
username: child.username,
check: child.check,
override: child.override
};
children.splice(++i, 0, newItem);
} // end if
if (!child.override && !child.check)
if (sameUsername[j].check) {
child.check = true;
}
}
} // end for (j)
}
我一直在以多种方式剖析此代码,但我无法使其正常工作。
我也有一些预期结果的测试数据(为了便于阅读,我会使用伪代码)
parameters:
[Parent("foo", true), Parent("foo", false), Parent("foo", true)]
[Child("foo", false, false)]
expected: => [Child("foo", true, false), Child("foo", false, true), Child("foo", true, false)]
result: never passing
parameters:
[Parent("foo", true)]
[Child("foo", false, false), Child("foo", false, false)]
expected: => [Child("foo", true, false), Child("foo", false, false)]
result: passing for length, not passing totally (check all properties)
parameters:
[Parent("foo", false), Parent("bar", true)]
[Child("foo", false, false)]
expected: => [Child("foo", false, false)]
result: never passing
parameters: (:any: means both true and false)
[Parent("foo", true)]
[Child("foo", :any:, true), Child("foo", false, false)]
expected: => [Child("foo", :any:, true), Child("foo", true, false)]
result: all passing for length, passing totally only for :all: = false