Is it possible to define an infix function?

后端 未结 5 961
不思量自难忘°
不思量自难忘° 2021-02-08 09:21

Is it possible to define my own infix function/operator in CoffeeScript (or in pure JavaScript)? e.g. I want to call

a foo b

or



        
5条回答
  •  醉酒成梦
    2021-02-08 10:09

    This is definitely not infix notation but it's kinda close : /

    let plus = function(a,b){return a+b};
    
    let a = 3;
    let b = 5;
    let c = a._(plus).b // 8
    

    I don't think anyone would actually want to use this "notation" since it's pretty ugly, but I think there are probably some tweaks that can be made to make it look different or nicer (possibly using this answer here to "call a function" without parentheses).

    Infix function

    // Add to prototype so that it's always there for you
    Object.prototype._ = function(binaryOperator){
    
      // The first operand is captured in the this keyword
      let operand1 = this; 
    
      // Use a proxy to capture the second operand with "get"
      // Note that the first operand and the applied function
      //   are stored in the get function's closure, since operand2
      //   is just a string, for eval(operand2) to be in scope,
      //   the value for operand2 must be defined globally
      return new Proxy({},{
        get: function(obj, operand2){
            return binaryOperator(operand1, eval(operand2))
        }
      })
    }
    

    Also note that the second operand is passed as a string and evaluated with eval to get its value. Because of this, I think the code will break anytime the value of operand (aka "b") is not defined globally.

提交回复
热议问题