使用indexOf重构两个方法

时间:2017-07-09 15:35:37

标签: javascript

这两种方法几乎相同,如何将它们重构为一种方法?

method1 = (value) => {
    var example =  array.filter(row => row.key.indexOf(value) > -1);
    this.setState({state: example});
}

method2 = (value) => {
    var example =  array.filter(row => row.otherKey.indexOf(value) > -1);
    this.setState({otherState: example});
}

1 个答案:

答案 0 :(得分:0)

取两个函数之间的差异,并通过使那些必须传递给函数的items参数将它与函数分开:

var method = (value, key, state) => {
    var example =  array.filter(row => row[key].indexOf(value) > -1);
    this.setState({state: example});
}