Skip to content

Commit

Permalink
Merge pull request #6 from AndreyBelym/proto-null
Browse files Browse the repository at this point in the history
Fix encoding/decoding when object has null as a proto
  • Loading branch information
inikulin authored Dec 17, 2018
2 parents 9e8a915 + c31578b commit a928834
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 20 deletions.
40 changes: 20 additions & 20 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,15 @@ EncodingTransformer.prototype._handleArray = function (arr) {
};

EncodingTransformer.prototype._handlePlainObject = function (obj) {
var result = Object.create(null);
var replicator = this;
var result = Object.create(null);
var ownPropertyNames = Object.getOwnPropertyNames(obj);

for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var resultKey = KEY_REQUIRE_ESCAPING_RE.test(key) ? '#' + key : key;
ownPropertyNames.forEach(function (key) {
var resultKey = KEY_REQUIRE_ESCAPING_RE.test(key) ? '#' + key : key;

result[resultKey] = this._handleValue(obj[key], result, resultKey);
}
}
result[resultKey] = replicator._handleValue(obj[key], result, resultKey);
});

return result;
};
Expand Down Expand Up @@ -170,20 +170,20 @@ var DecodingTransformer = function (references, transformsMap) {
};

DecodingTransformer.prototype._handlePlainObject = function (obj) {
var unescaped = Object.create(null);

for (var key in obj) {
if (obj.hasOwnProperty(key)) {
this._handleValue(obj[key], obj, key);

if (KEY_REQUIRE_ESCAPING_RE.test(key)) {
// NOTE: use intermediate object to avoid unescaped and escaped keys interference
// E.g. unescaped "##@t" will be "#@t" which can overwrite escaped "#@t".
unescaped[key.substring(1)] = obj[key];
delete obj[key];
}
var replicator = this;
var unescaped = Object.create(null);
var ownPropertyNames = Object.getOwnPropertyNames(obj);

ownPropertyNames.forEach(function (key) {
replicator._handleValue(obj[key], obj, key);

if (KEY_REQUIRE_ESCAPING_RE.test(key)) {
// NOTE: use intermediate object to avoid unescaped and escaped keys interference
// E.g. unescaped "##@t" will be "#@t" which can overwrite escaped "#@t".
unescaped[key.substring(1)] = obj[key];
delete obj[key];
}
}
});

for (var unsecapedKey in unescaped)
obj[unsecapedKey] = unescaped[unsecapedKey];
Expand Down
12 changes: 12 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,16 @@ describe('Regression', function () {

global.Uint8Array = savedUint8Array;
});

it('Should encode objects with null as a prototype', function () {
var obj = Object.create(null);

obj.foo = 'bar';
obj.ans = 42;

var actual = replicator.decode(replicator.encode(obj));

assert.strictEqual(actual.foo, 'bar');
assert.strictEqual(actual.ans, 42);
});
});

0 comments on commit a928834

Please sign in to comment.