Skip to content

Commit 1406e3c

Browse files
Create utility helper that inverts a JavaScript object
`invertObject` is a functional helper that swaps the key with the value for a JavaScript object. This utility helper will be used to invert the objects in React's HTMLDOMPropertyConfig in order to create a map for my parser. HTMLDOMPropertyConfig: https://github.com/facebook/react/blob/master/src/renderers/dom/shared/HTMLDOMPropertyConfig.js Tests added to ensure the helper works as expected.
1 parent 8db5a6b commit 1406e3c

File tree

2 files changed

+73
-1
lines changed

2 files changed

+73
-1
lines changed

lib/utilities.js

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,36 @@ function camelCase(string) {
2626
return string;
2727
}
2828

29+
/**
30+
* Swap key with value in an object.
31+
*
32+
* @param {Object} obj - The object.
33+
* @return {Object} - The inverted object.
34+
*/
35+
function invertObject(obj) {
36+
if (typeof obj !== 'object' || !obj) { // null is an object
37+
throw new Error('`invert`: First argument must be an object.');
38+
}
39+
40+
var result = {};
41+
var key;
42+
var value;
43+
44+
for (key in obj) {
45+
value = obj[key];
46+
if (typeof value === 'object') {
47+
throw new Error('`invert`: Object must be flat.');
48+
}
49+
result[value] = key;
50+
}
51+
52+
return result;
53+
}
54+
2955
/**
3056
* Export utilties.
3157
*/
3258
module.exports = {
33-
camelCase: camelCase
59+
camelCase: camelCase,
60+
invertObject: invertObject
3461
};

test/utilities.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,49 @@ describe('utilties', function() {
3333
})
3434
});
3535

36+
describe('`invertObject` helper', function() {
37+
var invertObject = utilities.invertObject;
38+
39+
it('swaps key with value for object', function() {
40+
assert.deepEqual(
41+
invertObject({ foo: 'bar', baz: 'qux' }),
42+
{ bar: 'foo', qux: 'baz' }
43+
);
44+
45+
// check for unusual cases
46+
assert.deepEqual(
47+
invertObject({
48+
$: 'dollar',
49+
_: 'underscore',
50+
num: 1,
51+
u: undefined
52+
}),
53+
{
54+
dollar: '$',
55+
underscore: '_',
56+
'1': 'num',
57+
'undefined': 'u'
58+
}
59+
);
60+
});
61+
62+
it('swaps key with value for array', function() {
63+
assert.deepEqual(
64+
invertObject(['zero', 'one']),
65+
{ 'zero': '0', 'one': '1' }
66+
);
67+
});
68+
69+
it('throws an error if the first argument is invalid', function() {
70+
[undefined, null, 'foo', 1337].forEach(function(parameter) {
71+
assert.throws(function() { invertObject(parameter); });
72+
});
73+
})
74+
75+
it('throws an error if object is not flat', function() {
76+
assert.throws(function() { invertObject({ nested: {} }); });
77+
assert.throws(function() { invertObject({ obj: null }); });
78+
})
79+
});
80+
3681
});

0 commit comments

Comments
 (0)