Skip to content

Commit

Permalink
fix(common): Re-fix implementation of 'pick' using for .. in
Browse files Browse the repository at this point in the history
Previous change to hasOwnProperty (released in 5.0.2) was not correct.

Closes #53
  • Loading branch information
christopherthielen committed May 7, 2017
1 parent 3ac52c1 commit f2da7f4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/common/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ export const mergeR = (memo: Obj, item: Obj) => extend(memo, item);
export function ancestors(first: StateObject, second: StateObject) {
let path: StateObject[] = [];

for (var n in first.path) {
for (let n in first.path) {
if (first.path[n] !== second.path[n]) break;
path.push(first.path[n]);
}
Expand All @@ -244,9 +244,13 @@ export function ancestors(first: StateObject, second: StateObject) {
* @param propNames an Array of strings, which are the whitelisted property names
*/
export function pick(obj: Obj, propNames: string[]): Obj {
let copy = {};
propNames.forEach(prop => { if (obj.hasOwnProperty(prop)) copy[prop] = obj[prop] });
return copy;
let objCopy = {};
for (let prop in obj) {
if (propNames.indexOf(prop) !== -1) {
objCopy[prop] = obj[prop];
}
}
return objCopy;
}

/**
Expand Down
14 changes: 14 additions & 0 deletions test/commonSpec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
defaults, filter, is, eq, not, pattern, val, isInjectable
} from "../src/index";
import { pick } from '../src/common/common';

describe('common', function() {
describe('filter', function() {
Expand Down Expand Up @@ -112,4 +113,17 @@ describe('common', function() {
expect(isInjectable(fn)).toBeTruthy();
});
});

describe('pick', () => {
it('should pick inherited properties', () => {
let parent = { foo: 'foo', bar: 'bar' };
let child = Object.create(parent);
expect(pick(child, ['foo'])).toEqual({ foo: 'foo' });
});

it('should not pick missing properties', () => {
let obj = { foo: 'foo', bar: 'bar' };
expect(pick(obj, ['baz'])).toEqual({ });
});
});
});

0 comments on commit f2da7f4

Please sign in to comment.