Is it possible to create custom operators in JavaScript?

后端 未结 9 1951
暖寄归人
暖寄归人 2020-12-03 04:20

During the Math classes we learned how to define new operators. For example:

(ℝ, ∘), x ∘ y = x + 2y

This defines law. For any r

9条回答
  •  孤街浪徒
    2020-12-03 05:19

    Given the somewhat new tagged template literals feature that was added in ES6 one can create custom DSLs to handle embedded expressions such as these including different algebraic symbols.

    ex. (run in stackblitz)

    function math(strings, x, y) {
      // NOTE: Naive approach as demonstration
    
      const operator = strings[1].replace(/\s/gi, "");
    
      if (operator == "∘") {
        return x + 2 * y;
      }
      else if (operator == "^") {
        return Math.pow(x, y);
      }
      else {
        return `Unknown operator '${operator}'`;
      }
    }
    
    console.log(math`${2} ∘ ${2}`)
    

    Note that since tagged template literals don't necessarily return strings as results they can return more complex intermediate AST like structures to build up an expression that can then be further refined and then interpreted while keeping close to the domain specific language at hand. I haven't found any existing library that does this yet for Javascript but it should be an interesting and quite approachable endeavor from what it appears from what I know of tagged template literals and usage in such places as lit-html.

提交回复
热议问题