2017-04-24 58 views
0

我正在爲項目數組構建一個裝飾器,如果對象數組適合那裏,則該對象數組將被分割爲一個定義的值範圍。遍歷一個對象或數組,以確定元素是否適合範圍

目前,我正在使用一些條件來檢查範圍,但代碼感覺不夠乾淨。

有沒有人有關如何以更簡潔和可擴展的方式編寫此代碼的任何建議?

當前設置舉例...

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

注:我真的通過這樣的邏輯尋找一種更好的方式來循環,並確定物體落在範圍。

+0

任何限制?你可以使用外部庫如lodash或下劃線嗎?你會瞄準ES5/ES6嗎? –

回答

0

我會先仔細檢查你的邏輯......

thingsToSort.forEach(function(thing) { 

此條件將設置什麼比1至1時,而忽略第二個條件(thing < 3):

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

你應該使用&&運營商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問題非常相似,其中有許多可能的重構

2

另一個實現。

  1. 生成的函數來表示的範圍內,Range
  2. 的函數,以確定的範圍內,並採取適當的行動。 setcompareRange

請注意在函數compareRange中使用some方法。由於只能在一個範圍內找到數字,所有範圍都不進行評估,直到完成匹配範圍遍歷。

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);