Skip to content

Commit 2f805ec

Browse files
SunJieMingSunJieMing
authored andcommitted
Added object solutions
1 parent cb56861 commit 2f805ec

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/objects.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,60 @@
11
// Complete the following underscore functions.
22
// Reference http://underscorejs.org/ for examples.
33

4+
/* eslint-disable no-unused-vars, arrow-body-style */
5+
46
const keys = (obj) => {
57
// Retrieve all the names of the object's properties.
68
// Return the keys as strings in an array.
79
// Based on http://underscorejs.org/#keys
10+
return Object.keys(obj);
811
};
912

1013
const values = (obj) => {
1114
// Return all of the values of the object's own properties.
1215
// Ignore functions
1316
// http://underscorejs.org/#values
17+
return Object.keys(obj).map((key) => {
18+
return obj[key];
19+
});
1420
};
1521

1622
const mapObject = (obj, cb) => {
1723
// Like map for arrays, but for objects. Transform the value of each property in turn.
1824
// http://underscorejs.org/#mapObject
25+
Object.keys(obj).forEach(key => (obj[key] = cb(obj[key])));
26+
return obj;
1927
};
2028

2129
const pairs = (obj) => {
2230
// Convert an object into a list of [key, value] pairs.
2331
// http://underscorejs.org/#pairs
32+
return Object.keys(obj).map((key) => {
33+
return [key, obj[key]];
34+
});
2435
};
2536

2637
const invert = (obj) => {
2738
// Returns a copy of the object where the keys have become the values and the values the keys.
2839
// Assume that all of the object's values will be unique and string serializable.
2940
// 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;
3047
};
3148

3249
const defaults = (obj, defaultProps) => {
3350
// Fill in undefined properties that match properties on the `defaultProps` parameter object.
3451
// Return `obj`.
3552
// 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;
3658
};
3759

3860
/* eslint-enable no-unused-vars */

0 commit comments

Comments
 (0)