src/arrayToObject.js   A
last analyzed

Complexity

Total Complexity 13
Complexity/F 2.17

Size

Lines of Code 52
Function Count 6

Duplication

Duplicated Lines 52
Ratio 100 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
c 1
b 0
f 0
nc 8
dl 52
loc 52
ccs 16
cts 16
cp 1
crap 0
rs 10
wmc 13
mnd 1
bc 9
fnc 6
bpm 1.5
cpm 2.1666
noi 0

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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