【问题标题】:Traverse an object or array to determine if elements fit within ranges遍历对象或数组以确定元素是否适合范围
【发布时间】:2017-04-24 18:51:38
【问题描述】:

我正在为项目数组构建一个装饰器,如果对象数组适合的话,它会被插入到定义的值范围中。

目前,我正在使用一些条件来检查范围,但代码对我来说不够干净。

有人对如何以更简洁和可扩展的方式编写此代码有任何建议吗?

当前设置示例...

thingsToSort.forEach(function(thing) {
    if (thing > 1 || thing < 3) {
        // set the item to 1
    }
    if (thing > 3 || thing < 5) {
        // set to 3
    }
})

注意:我真的在寻找一种更好的方法来循环这个逻辑并确定对象是否在范围内。

【问题讨论】:

  • 有什么限制吗?你可以使用像lodash或underscores这样的外部库吗?你会瞄准 ES5/ES6 吗?

标签: javascript angularjs arrays object


【解决方案1】:

另一个实现。

  1. 创建了一个函数来表示范围,Range
  2. 识别范围并采取适当措施的功能。 setcompareRange

注意函数compareRangesome 方法的使用。由于只能在一个范围内找到一个数字,因此不会评估所有范围,直到匹配的范围遍历完成。

function Range(min, max){
    this.min = min;
    this.max = max;
}

var rangeArray = [ new Range(1,3), new Range(3,5)];

function compareRange(c,i,arr){
    var result = rangeArray.some(x=> {
        return setcompareRange(c, x.min, x.max)
    });
}

function setcompareRange(thing, min, max){
    if (thing > min && thing < max) {
        // set the item to 1
        console.log("set thing = " + thing + " in range = " + min);
        return true;
    }
}

var thingsToSort = [2,4];
thingsToSort.forEach(compareRange);

【讨论】:

    【解决方案2】:

    我会先仔细检查你的逻辑......

    thingsToSort.forEach(function(thing) {
    

    此条件会将大于 1 的 ANYTHING 设置为 1,并忽略第二个条件 (thing &lt; 3):

        if (thing > 1 || thing < 3) {
            // set the item to 1
        }
    

    您应该使用&amp;&amp; 运算符来AND 这两个条件:

        if (thing > 1 && thing < 3) {
            // set the item to 1
        }
    

    同样的事情也适用于这个条件,它将任何大于 3 的东西设置为 3。

        if (thing > 3 || thing < 5) {  //should be &&
            // set to 3
        }
    })
    

    你也没有在满足条件后打破循环。这意味着即使您已经确定一个事物满足第一个条件,您仍在检查它是否满足其他条件。这会浪费资源。使用else if 来防止这种情况:

        if (thing > 1 && thing < 3) {
            // set the item to 1
        }
        else if (thing > 3 && thing < 5) {
            // set to 3
        }
    

    除此之外,它已经很干净了。这与经典的fizzbuzz 问题非常相似,其中,有很多可能的重构

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      相关资源
      最近更新 更多