| Conditions | 6 |
| Paths | 1 |
| Total Lines | 52 |
| Lines | 52 |
| Ratio | 100 % |
| Tests | 16 |
| CRAP Score | 6 |
| Changes | 1 | ||
| Bugs | 0 | Features | 1 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | /** |
||
| 18 | 1 | View Code Duplication | module.exports = function(arr, mapBy) { |
|
1 ignored issue
–
show
|
|||
| 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 |