不同长度列表的父/子逻辑

时间:2018-03-06 18:40:49

标签: javascript

我有两个不同长度的列表

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 }
];

这些列表与此规则相关:(密钥是用户名)

  • 如果有很多父母带钥匙,并且孩子使用相同的钥匙,请在儿童列表中再添加2个孩子
  • 如果有一个父母和多个孩子按密钥链接,则子项列表不会更改
到目前为止的

代码

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

0 个答案:

没有答案