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