Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(*): add support for toJSON method #8

Merged
merged 1 commit into from
Jul 31, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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