|
1 | 1 | // Complete the following underscore functions. |
2 | 2 | // Reference http://underscorejs.org/ for examples. |
3 | 3 |
|
| 4 | +/* eslint-disable no-unused-vars, arrow-body-style */ |
| 5 | + |
4 | 6 | const keys = (obj) => { |
5 | 7 | // Retrieve all the names of the object's properties. |
6 | 8 | // Return the keys as strings in an array. |
7 | 9 | // Based on http://underscorejs.org/#keys |
| 10 | + return Object.keys(obj); |
8 | 11 | }; |
9 | 12 |
|
10 | 13 | const values = (obj) => { |
11 | 14 | // Return all of the values of the object's own properties. |
12 | 15 | // Ignore functions |
13 | 16 | // http://underscorejs.org/#values |
| 17 | + return Object.keys(obj).map((key) => { |
| 18 | + return obj[key]; |
| 19 | + }); |
14 | 20 | }; |
15 | 21 |
|
16 | 22 | const mapObject = (obj, cb) => { |
17 | 23 | // Like map for arrays, but for objects. Transform the value of each property in turn. |
18 | 24 | // http://underscorejs.org/#mapObject |
| 25 | + Object.keys(obj).forEach(key => (obj[key] = cb(obj[key]))); |
| 26 | + return obj; |
19 | 27 | }; |
20 | 28 |
|
21 | 29 | const pairs = (obj) => { |
22 | 30 | // Convert an object into a list of [key, value] pairs. |
23 | 31 | // http://underscorejs.org/#pairs |
| 32 | + return Object.keys(obj).map((key) => { |
| 33 | + return [key, obj[key]]; |
| 34 | + }); |
24 | 35 | }; |
25 | 36 |
|
26 | 37 | const invert = (obj) => { |
27 | 38 | // Returns a copy of the object where the keys have become the values and the values the keys. |
28 | 39 | // Assume that all of the object's values will be unique and string serializable. |
29 | 40 | // http://underscorejs.org/#invert |
| 41 | + Object.keys(obj).forEach((key) => { |
| 42 | + const newKey = obj[key]; |
| 43 | + obj[newKey] = key; |
| 44 | + delete obj[key]; |
| 45 | + }); |
| 46 | + return obj; |
30 | 47 | }; |
31 | 48 |
|
32 | 49 | const defaults = (obj, defaultProps) => { |
33 | 50 | // Fill in undefined properties that match properties on the `defaultProps` parameter object. |
34 | 51 | // Return `obj`. |
35 | 52 | // http://underscorejs.org/#defaults |
| 53 | + Object.keys(defaultProps).forEach((key) => { |
| 54 | + if (Object.prototype.hasOwnProperty.call(obj, key)) return; |
| 55 | + obj[key] = defaultProps[key]; |
| 56 | + }); |
| 57 | + return obj; |
36 | 58 | }; |
37 | 59 |
|
38 | 60 | /* eslint-enable no-unused-vars */ |
|
0 commit comments