Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow prefixes within keyMirror #4228

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/shared/vendor/key-mirror/__tests__/keyMirror-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,23 @@ describe('keyMirror', function() {
expect('qux' in mirror).toBe(true);
expect(mirror.qux).toBe('qux');
});

it('should create an object with prefixed values matching keys provided when a prefix argument is supplied', function() {
var mirror = keyMirror({
foo: null,
bar: true,
"baz": {some: "object"},
qux: undefined
}, 'foo_');
expect('foo' in mirror).toBe(true);
expect(mirror.foo).toBe('foo_foo');
expect('bar' in mirror).toBe(true);
expect(mirror.bar).toBe('foo_bar');
expect('baz' in mirror).toBe(true);
expect(mirror.baz).toBe('foo_baz');
expect('qux' in mirror).toBe(true);
expect(mirror.qux).toBe('foo_qux');
});

it('should not use properties from prototypes', function() {
function Klass() {
Expand All @@ -53,6 +70,14 @@ describe('keyMirror', function() {
expect(keyMirror.bind(null, testVal)).toThrow();
});
});

it('should throw when a non-string prefix argument is used', function() {
[null, undefined, 0, 7, ['uno'], true, "string"].forEach(function(testVal) {
expect(keyMirror.bind(null, testVal, 1)).toThrow();
expect(keyMirror.bind(null, testVal, [])).toThrow();
expect(keyMirror.bind(null, testVal, {})).toThrow();
});
});

it('should work when "constructor" is a key', function() {
var obj = {constructor: true};
Expand Down
9 changes: 7 additions & 2 deletions src/shared/vendor/key-mirror/keyMirror.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,25 @@ var invariant = require('invariant');
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @param {string} prefix
* @return {object}
*/
var keyMirror = function(obj) {
var keyMirror = function(obj, prefix = '') {
var ret = {};
var key;
invariant(
obj instanceof Object && !Array.isArray(obj),
'keyMirror(...): Argument must be an object.'
);
invariant(
typeof prefix === 'string',
'keyMirror(...): Prefix must be a string.'
);
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
ret[key] = prefix + key;
}
return ret;
};
Expand Down