Extend JavaScript object with default function

In google app scripts, I have a one-dimensional data array that I can get values ​​from this:

data[0]

I would like to pass the name of the column, namely:

data("A")

Thus, I do not need to convert the letters to their position in the array. Therefore, I would like to expand the array object (the extension is not risky, since it works in an isolated script environment).

I know that I can add a function to the prototype of the array using this letter for the number function and this question of expanding the object like this:

Array.prototype.byCol = function(colName) {
  return this[getColumnNumber(colName) - 1];
}

function getColumnNumber(str) {
  var out = 0, len = str.length;
  for (pos = 0; pos < len; pos++) {
    out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - pos - 1);
  }
  return out;
}

var data = [1,2,3,4];

document.write(data.byCol("B"));
Run codeHide result

But this is a bit more complicated call syntax than I wanted.

, , , , :

var test = new func(function() {
    // do something
});

, ?

+4
1

, - , , .

, -, , , :

var wrapper = (function() {
  function getColumnNumber(str) {
    return Array.prototype.reduce.call(str.toUpperCase(), function (t, c) {
        return 26 * t + c.charCodeAt(0) - 64;
    }, 0) - 1;
  }

  return function(arr) {
    return function(col, val) {
      if (arguments.length === 0) {
        return arr;
      }
      if (arguments.length > 1) {
        arr[getColumnNumber(col)] = val;
      }
      return arr[getColumnNumber(col)];
    };
  };
})();

var w = wrapper([10, 20, 30, 40, 50]);

snippet.log(w('D')); // 40

w('D', 33);          // set value

snippet.log(w('D')); // 33

w()[3] = 42;         // access underlying array directly
w().push(60);

snippet.log(w('D')); // 42
snippet.log(w('F')); // 60
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script>
Hide result
+3

All Articles