Fix immutability helper to check hasOwnProperty safely
This makes `update({}, {'hasOwnProperty': {$set: 'yolo'}})` work.
Jeff Chan committed
Apr 1, 2015 at 12:05 UTC
af7e43269f24d2854dc8bec40aae58d659ee579c
2 files changed
+15
-6
src/addons/__tests__/update-test.js
+6
@@ -93,4 +93,10 @@ describe('update', function() {
93
'$apply. Did you forget to include {$set: ...}?'
94
);
95
});
96
+
97
+ it('should perform safe hasOwnProperty check', function() {
98
+ expect(update({}, {'hasOwnProperty': {$set: 'a'}})).toEqual({
99
+ 'hasOwnProperty': 'a'
100
+ });
101
+ });
102
});
src/addons/update.js
+9
-6
@@ -9,11 +9,14 @@
9
* @providesModule update
10
*/
11
12
+ /* global hasOwnProperty:true */
13
+
14
'use strict';
15
16
var assign = require('Object.assign');
17
var keyOf = require('keyOf');
18
var invariant = require('invariant');
19
+var hasOwnProperty = {}.hasOwnProperty;
20
21
function shallowCopy(x) {
22
if (Array.isArray(x)) {
@@ -73,7 +76,7 @@ function update(value, spec) {
76
COMMAND_SET
77
);
78
76
- if (spec.hasOwnProperty(COMMAND_SET)) {
79
+ if (hasOwnProperty.call(spec, COMMAND_SET)) {
80
invariant(
81
Object.keys(spec).length === 1,
82
'Cannot have more than one key in an object with %s',
@@ -85,7 +88,7 @@ function update(value, spec) {
88
89
var nextValue = shallowCopy(value);
90
88
- if (spec.hasOwnProperty(COMMAND_MERGE)) {
91
+ if (hasOwnProperty.call(spec, COMMAND_MERGE)) {
92
var mergeObj = spec[COMMAND_MERGE];
93
invariant(
94
mergeObj && typeof mergeObj === 'object',
@@ -102,21 +105,21 @@ function update(value, spec) {
105
assign(nextValue, spec[COMMAND_MERGE]);
106
}
107
105
- if (spec.hasOwnProperty(COMMAND_PUSH)) {
108
+ if (hasOwnProperty.call(spec, COMMAND_PUSH)) {
109
invariantArrayCase(value, spec, COMMAND_PUSH);
110
spec[COMMAND_PUSH].forEach(function(item) {
111
nextValue.push(item);
112
});
113
}
114
112
- if (spec.hasOwnProperty(COMMAND_UNSHIFT)) {
115
+ if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) {
116
invariantArrayCase(value, spec, COMMAND_UNSHIFT);
117
spec[COMMAND_UNSHIFT].forEach(function(item) {
118
nextValue.unshift(item);
119
});
120
}
121
119
- if (spec.hasOwnProperty(COMMAND_SPLICE)) {
122
+ if (hasOwnProperty.call(spec, COMMAND_SPLICE)) {
123
invariant(
124
Array.isArray(value),
125
'Expected %s target to be an array; got %s',
@@ -142,7 +145,7 @@ function update(value, spec) {
145
});
146
}
147
145
- if (spec.hasOwnProperty(COMMAND_APPLY)) {
148
+ if (hasOwnProperty.call(spec, COMMAND_APPLY)) {
149
invariant(
150
typeof spec[COMMAND_APPLY] === 'function',
151
'update(): expected spec of %s to be a function; got %s.',