如何优化此switch语句?

abu*_*uba 4 javascript optimization

我尝试在我的应用程序中使用,简单的比较器通过传递字符串过滤器来过滤一些数据而不是例如.传递给[].filter Comparator应该返回一个过滤器的函数.

   var comparator = function( a, b, c ) { 
        switch( b ){
            case '>=': return function() { return this[a] >= c;}; break;
            case '<=': return function() { return this[a] <= c;}; break;
            case '<':  return function() { return this[a] < c;}; break;
            case '>':  return function() { return this[a] > c;}; break;
            case '=':  return function() { return this[a] == c;}; break;
            case '==': return function() { return this[a] === c;}; break;
            case '!=': return function() { return this[a] != c;}; break;
            default: return null;
        };

    }
Run Code Online (Sandbox Code Playgroud)

假设我通过以下方式获得此功能:

  var filterFn = comparator.apply({}, /(.+)(=|>=|<=|<|>|!=|==|!==)(.+)/.exec( "id<4" ).slice(1) );


  someModel = someModel.objects.filter( filterFn );
Run Code Online (Sandbox Code Playgroud)

它看起来的目标:

   someModel.get = function( filter ){ 
      return new Model(  
           this.objects.filter(
               comparator.apply({}, /(.+)(=|>=|<=|<|>|!=|==|!==)(.+)/.exec( "id<4" ).slice(1) 
           ) 
      );
   };
   var filtered = someModel.get( "id<4" );
Run Code Online (Sandbox Code Playgroud)

问题是 - 我认为这将是更多的运营商,我不知道如何更简单地写它.

使用Eval是不可能的.

这段代码没有被执行和测试我写它只是为了表明我的意思.

Rob*_*b W 5

将每个函数存储在对象中,可以是预定义的,也可以是动态的.

如果要动态创建函数集,请comparator按如下所示定义对象.我以为你没有扩展Object.prototype.如果你这样做,operators.hasOwnProperty(property)必须在第一个循环中使用.

// Run only once
var funcs = {};   // Optionally, remove `funcs` and swap `funcs` with `operators`
var operators = { // at the first loop.
    '>=': '>=',
    '<=': '<=',
    '<' :  '<',
    '>' :  '>',
    '=' : '==', //!!
    '==':'===', //!!
    '!=': '!='
}; // Operators

// Function constructor used only once, for construction
for (var operator in operators) {
    funcs[operator] = Function('a', 'c',
                       'return function() {return this[a] ' + operator + ' c};');
}

// Run later
var comparator = function(a, b, c) {
    return typeof funcs[b] === 'function' ? funcs[b](a, c) : null;
};
Run Code Online (Sandbox Code Playgroud)

comparator被调用时,返回的功能是这样的:

function() {  return this[a] < c;   }// Where a, c are pre-determined.
Run Code Online (Sandbox Code Playgroud)

这种方法可以用这种方式实现(JSFiddle演示):

// Assumed that funcs has been defined
function implementComparator(set, key, operator, value) {
    var comparator, newset = [], i;

    if (typeof funcs[operator] === 'function') {
        comparator = funcs[operator](key, value);
    } else { //If the function does not exist...
        throw TypeError("Unrecognised operator");
    }

    // Walk through the whole set
    for (i = 0; i < set.length; i++) {
        //  Invoke the comparator, setting `this` to `set[i]`. If true, push item
        if (comparator.call(set[i])) {
            newset.push(set[i]);
        }
    }
    return newset;
}
var set = [ {meow: 5}, {meow: 3}, {meow: 4}, {meow: 0}, {meow: 9}]
implementComparator( set , 'meow', '<=', 5);
// equals: [ {meow: 5}, {meow: 3}, {meow: 4}, {meow: 0} ]
Run Code Online (Sandbox Code Playgroud)

为了澄清,我构建了这个答案,同时牢记以下内容:

  • OP使用未知/动态的运算符集请求简单,易于扩展的方法.
  • 代码基于OP处的伪代码,而不会改变任何可能影响OP意图的内容.通过一些调整,此功能也可用于Array.prototype.filterArray.prototype.sort.
  • eval(或Function)不应在每次通话时使用comparator