Skip to content

Commit

Permalink
feat(*): add support for toJSON method (#8)
Browse files Browse the repository at this point in the history
Closes #7
  • Loading branch information
darrachequesne authored Jul 31, 2017
1 parent 6c1dca3 commit 9345f9f
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions browser/encode.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,10 @@ function _encode(bytes, defers, value) {
return size + length;
}

if (typeof value.toJSON === 'function') {
return _encode(bytes, defers, value.toJSON());
}

var keys = [], key = '';

var allKeys = Object.keys(value);
Expand Down
4 changes: 4 additions & 0 deletions lib/encode.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,10 @@ function _encode(bytes, defers, value) {
return size + length;
}

if (typeof value.toJSON === 'function') {
return _encode(bytes, defers, value.toJSON());
}

var keys = [], key = '';

var allKeys = Object.keys(value);
Expand Down
11 changes: 11 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,18 @@ describe('notepack', function () {
expect(notepack.decode(encoded)).to.deep.equal(map32);
});

it('toJSON', function () {
var obj = {
a: 'b',
toJSON: function () {
return 'c';
}
}
expect(notepack.encode(obj)).to.deep.equal(notepack.encode('c'));
});

it('all formats', function () {
this.timeout(20000);
var expected = {
unsigned: [1, 2, 3, 4, { b: { c: [128, 256, 65536, 4294967296] } }],
signed: [-1, -2, -3, -4, { b: { c: [-33, -129, -32769, -2147483649] } }],
Expand Down

0 comments on commit 9345f9f

Please sign in to comment.