Skip to content

Commit f2da7f4

Browse files
fix(common): Re-fix implementation of 'pick' using for .. in
Previous change to hasOwnProperty (released in 5.0.2) was not correct. Closes #53
1 parent 3ac52c1 commit f2da7f4

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

src/common/common.ts

+8-4
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ export const mergeR = (memo: Obj, item: Obj) => extend(memo, item);
225225
export function ancestors(first: StateObject, second: StateObject) {
226226
let path: StateObject[] = [];
227227

228-
for (var n in first.path) {
228+
for (let n in first.path) {
229229
if (first.path[n] !== second.path[n]) break;
230230
path.push(first.path[n]);
231231
}
@@ -244,9 +244,13 @@ export function ancestors(first: StateObject, second: StateObject) {
244244
* @param propNames an Array of strings, which are the whitelisted property names
245245
*/
246246
export function pick(obj: Obj, propNames: string[]): Obj {
247-
let copy = {};
248-
propNames.forEach(prop => { if (obj.hasOwnProperty(prop)) copy[prop] = obj[prop] });
249-
return copy;
247+
let objCopy = {};
248+
for (let prop in obj) {
249+
if (propNames.indexOf(prop) !== -1) {
250+
objCopy[prop] = obj[prop];
251+
}
252+
}
253+
return objCopy;
250254
}
251255

252256
/**

test/commonSpec.ts

+14
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
defaults, filter, is, eq, not, pattern, val, isInjectable
33
} from "../src/index";
4+
import { pick } from '../src/common/common';
45

56
describe('common', function() {
67
describe('filter', function() {
@@ -112,4 +113,17 @@ describe('common', function() {
112113
expect(isInjectable(fn)).toBeTruthy();
113114
});
114115
});
116+
117+
describe('pick', () => {
118+
it('should pick inherited properties', () => {
119+
let parent = { foo: 'foo', bar: 'bar' };
120+
let child = Object.create(parent);
121+
expect(pick(child, ['foo'])).toEqual({ foo: 'foo' });
122+
});
123+
124+
it('should not pick missing properties', () => {
125+
let obj = { foo: 'foo', bar: 'bar' };
126+
expect(pick(obj, ['baz'])).toEqual({ });
127+
});
128+
});
115129
});

0 commit comments

Comments
 (0)