aboutsummaryrefslogtreecommitdiffstats
path: root/lib/utils.js
blob: 7fc2a6b92e95fd086ba1bc2824a8914c3b0691b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
var utils = {
  // probably doesn't handle some cases correctly, but it works fine for what
  // we have now
  deepCopy: function(original) {
    var result;
    if (typeof original == 'object') {
      if (original === null) {
        result = null;
      } else {
        result = original.constructor === Array ? [] : {};
        for (var i in original)
          if (original.hasOwnProperty(i))
            result[i] = this.deepCopy(original[i]);
      }
    } else {
      result = original;
    }

    return result;
  },

  /*
   * Extends 'original' with 'ext'. If a function in 'ext' also exists in
   * 'original', let the 'original' function be accessible in the new object
   * via a  ._super(functionName as String) method. _Cannot_ be used on its
   * result to achieve 'two-level' inheritance.
   */
  extendWithSuper: function(original, ext) {
    var result = this.deepCopy(original);
    var tmpSuper = result._super;
    result._superFunctions = {};
    result._super = function(fname) { return this._superFunctions[fname].bind(this); }
    for (var i in ext)
      if (ext.hasOwnProperty(i)) {
        if (typeof ext[i] == 'function' && typeof original[i] == 'function')
          result._superFunctions[i] = this.deepCopy(original[i]);
        result[i] = this.deepCopy(ext[i]);
      }
    return result;
  },

  /*
   * Takes a dot-notation object string and call the function
   * that it points to with the correct value for 'this'.
   */
  invokeCommandString: function(str, argArray) {
    var components = str.split('.');
    var obj = window;
    for (var i = 0; i < components.length - 1; i++)
      obj = obj[components[i]];
    var func = obj[components.pop()];
    return func.apply(obj, argArray);
  },
};