understanding decision table in javascript

前端 未结 2 2039
温柔的废话
温柔的废话 2021-01-28 13:48

I was just going through the code of Jbox and cam across the following snippet of code:

// Internal functions, used to easily get values
    this._getOpp = func         


        
相关标签:
2条回答
  • 2021-01-28 14:08

    It's a technique that I know as a decision table (a wrote a blog post about them a while ago), but other might call it by different names.

    It uses the square bracket notation in the same way you'd reference the index of an array:

    var arr = [0, 2, 3];
    return arr[1]; // return the second value in the array
    

    Because object properties are key/value pairs it works like this:

      return {
        left: 'right', 
        right: 'left', 
        top: 'bottom', 
        bottom: 'top',
        x: 'y', 
        y: 'x'
      }[opp]
    

    It will actually return the string value, to the key opp.

    i.e. if opp is 'right', it will return 'left'.

    n.b. the wiki page on decision tables is also worth a read

    0 讨论(0)
  • 2021-01-28 14:13

    It creates an object with values first, then return a specific attr in the object whose key is the given opp. And if no such key is founded, undefined is returned.

    You can see them as :

    var states= {
        left: 'right', 
        right: 'left', 
        top: 'bottom', 
        bottom: 'top',
        x: 'y', 
        y: 'x'
    };
    return settings[opp];
    

    The snippet shows how it would act.

    var getOpp = function(opp) { 
          return {left: 'right', 
          right: 'left', 
          top: 'bottom', 
          bottom: 'top',
          x: 'y', 
          y: 'x'}[opp]; 
    };
    
    console.log(getOpp('right'));
    console.log(getOpp('oops'));

    0 讨论(0)
提交回复
热议问题