2016-09-17 90 views
0

最近我開始學習重構代碼。我如何重構這段代碼。我可以從哪裏開始?如何重構這段代碼?

var activeNumber = [ 
    { name: 'no 1' }, 
    { name: 'no 2' }, 
    { name: 'no 11' }, 
    { name: 'no 3' }, 
    { name: 'no 10' } 
]; 

var numberRe = new RegExp('\\d+'); 

var getCustomNumber = function() { 
    var top = 0; 
    for (var i = 0; i < activeNumber.length; i++) { 
     var present = numberRe.exec(activeNumber[i].name); 
     if (present) { 
      var neno = parseInt(present[0]); 
      if (!isNaN(neno) && neno > top) { 
       top = neno; 
      } 
     } 
    } 
    return top; 
}; 

回答

0

看來你是要找到中的對象的列表中name財產MAX(最高)數。
使用以下方法優化:

var activeNumber = [ 
 
    {name: 'no 1'}, 
 
    {name: 'no 2'}, 
 
    {name: 'no 11'}, 
 
    {name: 'no 3'}, 
 
    {name: 'no 10'} 
 
]; 
 

 
var getMaxNumber = function(arr) { 
 
    var top = 0, items = []; 
 
    if (Array.isArray(arr) && arr.length === 0) return top; 
 

 
    arr.forEach(function(o) { 
 
    num = o.name.match(/\d+/); // finds matches for a number in 'name' property 
 
    if (num) items.push(num); 
 
    }); 
 

 
    return Math.max.apply(null, items); // gets the maximum value of the list 
 
} 
 

 
console.log(getMaxNumber(activeNumber));

0
var getCustomerNumber = function (custNumber) { 
    var present = numberRe.exec(custNumber); 
    if (present) { 
     return parseInt(present[0]); 
    } 
    return -1; 
}; 

var getAllCustomerNumbers = function (customers) { 
    var top = 0; 
    for (var i = 0; i < customers.length; i++) { 
     var neno = getCustomerNumber(customers[i].name); 
     if (!isNaN(neno) && neno > top) { 
      top = neno; 
     } 
    } 
    return top; 
}; 

我希望我沒有做任何的錯誤。

一個簡單的規則是創建只能做一件事的代碼段。在上面的例子中,一個函數負責從正則表達式的字符串中提取數字,即getCustomerNumber,另一個函數是迭代許多客戶並提取他們的數字。

此外,通過爲您的功能,所有的依賴關係的爭論在這種情況下customerscustNumber是有用的,其原因是,你可以讓你的代碼可測試(特別是單元測試),因爲你通過一切,它需要跑。