2017-07-31 56 views
0

功能getRegistry()創建具有多個屬性註冊表對象,它們共享相同的結構在JavaScript:如何在下面的行`value:_value(this.from,this.to,line)`上獲得DRY?

'use strict' 

function getRegistry(line) { 
    return { 
    systemId: { 
     from: 1, to: 3, 
     name: 'system_id', 
     value: _value(this.from, this.to, line) 
    }, 
    originUnity: { 
     from: 4, to: 7, 
     name: 'origin_unity', 
     value: _value(this.from, this.to, line) 
    }, 
    // ... similar property definition as above 
    } 
} 

function _value (from, to, line) { 
    return line.substring(from - 1, to) 
} 

module.exports = getRegistry 

如何更改屬性定義在該行value: _value(this.from, this.to, line)所以要去除代碼重複?

回答

1

的代碼看起來並不馬虎,我...但如果你真的想爲代碼儘可能高效,這是我看到的唯一的改進:

function getRegistry(line) { 
     return { 
     systemId: { 
      from: 1, to: 3, 
      name: 'system_id', 
      value: _value(this, line) 
     }, 
     originUnity: { 
      from: 4, to: 7, 
      name: 'origin_unity', 
      value: _value(this, line) 
     }, 
     // ... similar property definition as above 
     } 
    } 

    function _value (obj, line) { 
     return line.substring(obj.from - 1, obj.to) 
    } 
+0

不錯!這是目前的工作,因爲它是第一個目標草案。 – ranieribt