簡體   English   中英

如何重構此代碼?

[英]How to refactor this code?

最近,我開始學習重構代碼。 我該如何重構此代碼。 我從哪里開始?

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

似乎您正在嘗試在對象列表中的name屬性內找到最大(最高)數。
使用以下優化方法:

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

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所有依賴關系作為函數的參數傳遞也是有用的,其原因是因為可以傳遞代碼運行所需的所有內容,因此可以使代碼可測試(特別是單元可測試)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM