Skip to content

Commit

Permalink
Add property symbols
Browse files Browse the repository at this point in the history
  • Loading branch information
superman2211 committed Jan 28, 2023
1 parent 37a8539 commit dd3afa5
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/fresh-chefs-study.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@xobj/core": minor
---

Add property symbols
10 changes: 9 additions & 1 deletion packages/core/src/encoders/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { EncodeContext } from '../encode';
export function encodeObject(value: any, context: EncodeContext): void {
const { writer, links } = context;
links.push(value);
const keys = Object.keys(value);

const keys = Object.getOwnPropertyNames(value);
for (const key of keys) {
const number = parseFloat(key);
if (Number.isInteger(number)) {
Expand All @@ -15,5 +16,12 @@ export function encodeObject(value: any, context: EncodeContext): void {
}
encodeValue(value[key], context);
}

const symbols = Object.getOwnPropertySymbols(value);
for (const symbol of symbols) {
encodeValue(symbol, context);
encodeValue(value[symbol], context);
}

writer.writeUintVar(ValueType.END);
}
22 changes: 22 additions & 0 deletions packages/core/test/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,26 @@ describe('object', () => {
const jsonData = new TextEncoder().encode(JSON.stringify(source));
expect(jsonData.byteLength).toBeGreaterThan(buffer.byteLength);
});

it('should write object with symbols', () => {
const s1 = Symbol('one');
const s2 = Symbol('two');

const source = {
one: 11,
11: 'one',
symbols: [s1, s2],
[s1]: 'symbol one',
[s2]: 'symbol two',
};

const buffer = encode(source);

const target = decode(buffer);

expect(target.one).toBe(source.one);
expect(target[11]).toBe(source[11]);
expect(target[target.symbols[0]]).toBe('symbol one');
expect(target[target.symbols[1]]).toBe('symbol two');
});
});

0 comments on commit dd3afa5

Please sign in to comment.