Passed
Branch master (305f3f)
by Eric
01:06
created

dist/arrayToObject.js   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 1

Duplication

Lines 1
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
c 1
b 0
f 0
nc 6
nop 1
dl 1
loc 1
rs 5.3846
1 View Code Duplication
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.arrayToObject = f()}})(function(){var define,module,exports;module={exports:(exports={})};
2
/**
3
 * Turns an Array into an associative Object (while keeping reference!)
4
 *
5
 * @param {Array}                 arr    Array of Objects to turn into an
6
 *                                       associative Object
7
 * @param {String|Array|Function} mapBy  optional mapping key, can be a
8
 *                                       simple string (property name in
9
 *                                       the abjects of arr), a list of
10
 *                                       property names (which are
11
 *                                       combined) or a function which
12
 *                                       returns a unique id to use
13
 *
14
 * @throws {TypeError} if arr is not an Array or mapBy is set but not of
15
 *                     correct type (String, Array, Function)
16
 *
17
 * @returns {Object}
18
 */
19
module.exports = function(arr, mapBy) {
20
  var obj = {};
21
22
  if (!Array.isArray(arr)) {
23
    throw new TypeError('arr argument is not of type Array');
24
  }
25
26
  if (mapBy !== undefined
27
    && typeof mapBy !== 'string'
28
    && !Array.isArray(mapBy)
29
    && typeof mapBy !== 'function'
30
  ) {
31
    throw new TypeError(
32
      'mapBy argument is not of type {String|Array|Function}'
33
    );
34
  }
35
36
  var methods = {
37
    string: function(val) {
38
      this.undefined(val, val[mapBy]);
39
    },
40
    object: function(val) {
41
      var newKey = mapBy.map(function(propertyName){
42
        return val[propertyName];
43
      }).join('_');
44
45
      this.undefined(val, newKey);
46
    },
47
    function: function(val, i, arr) {
48
      this.undefined(val, mapBy(val, i, arr));
49
    },
50
    undefined: function(val, newKey) {
51
      if (typeof newKey === 'string'
52
        || typeof newKey === 'number'
53
      ) {
54
        obj[newKey] = val;
55
      }
56
    }
57
  };
58
59
  /**
60
   * run the designated method by mapBy type from the methods object
61
   * it binds the methods object so we can use the undefined setter method
62
   * for different mapBy types and don't have to maintain multiple but
63
   * same conditions
64
   */
65
  arr.forEach(
66
    methods[(typeof mapBy)].bind(methods)
67
  );
68
69
  return obj;
70
};
71
72
return module.exports;});
73