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

Add uniformer #119

Merged
merged 11 commits into from
Jan 7, 2022
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
47 changes: 47 additions & 0 deletions lib/util/uniformer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
type KeyValuePair = [ string, unknown ];
type Primitive = Array<unknown> | string | number | symbol | boolean | null;

export default class Uniformer {

public formString(obj: unknown | Primitive ): string {
const sortedEntries = this.walk(obj);
return JSON.stringify(sortedEntries);
}

private toSortedKeyValuePairs(obj: unknown) {
const toKeyValueTuple = ([k, v]): KeyValuePair => [k, this.walk(v)];
const sortByKey = (a: KeyValuePair, b: KeyValuePair) => ("" + a[0]).localeCompare(b[0]);

const properties = Object.entries(obj as Record<string, unknown>);

return properties
.map(toKeyValueTuple)
.sort(sortByKey);
}

private getSymbolName(symbol: string) {
return symbol.slice("Symbol(".length, -1); // Extracts 'foo' from 'Symbol(foo)'
}

private walk(obj: unknown | Primitive ): KeyValuePair[] | Primitive {
switch(typeof obj) {
case "string":
case "number":
case "boolean": return obj;
case "symbol": return this.getSymbolName(obj.toString());
case "object":
if(obj === null)
return null;

if(obj instanceof Array)
return obj.map(e => this.walk(e));

if(obj instanceof Date)
return obj.toISOString();

return this.toSortedKeyValuePairs(obj);
default:
throw new Error(`Unknown parameter type '${typeof obj}.`);
}
}
}
98 changes: 98 additions & 0 deletions test/uniformer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { expect } from 'chai';
import Uniformer from '../lib/util/uniformer';

describe('Uniformer', () => {
context('when object is a Hash', () => {
it('(deep) sorts hashes by keys and converts keys to string', async () => {
const unsortedProperties = {
b: 2,
a: 1,
c: {
c3: 'c',
c2: 'b',
c1: 'a'
}
};

const result = new Uniformer().formString(unsortedProperties);

expect(result).to.equal(JSON.stringify([
['a', 1],
['b', 2],
['c', [
['c1', 'a'],
['c2', 'b'],
['c3', 'c']
]
]
]));
})
});

context('when object is a Symbol', () => {
it('converts symbol values to strings', () => {
const input1 = { test: Symbol('foobar') };
const input2 = { test: Symbol.for('foobar') };

expect(new Uniformer().formString(input1))
.to.equal(JSON.stringify([[ 'test', 'foobar']]));

expect(new Uniformer().formString(input2))
.to.equal(JSON.stringify([[ 'test', 'foobar']]));
});
});

context('when object is a DateTime', () => {
it('converts to a string in ISO8601 UTC using milliseconds', () => {
const someDate = new Date("2020-06-08T23:59:30.849+0200");

expect(new Uniformer().formString(someDate))
.to.equal(JSON.stringify('2020-06-08T21:59:30.849Z'));
});
});

it('allows integers, booleans and null', () => {
const uniformer = new Uniformer();

const values = [42, -1, true, false, null];
values.forEach((value) => {
expect(uniformer.formString(value))
.to.equal(JSON.stringify(value));
})
});

context('when object is an Array', () => {
it('allows arrays', () => {
const input = ['1', 2, 3];

expect(new Uniformer().formString(input))
.to.equal('[\"1\",2,3]');
});
});

it('applies rules to nested objects', () => {
const input = {
string: 'a string',
array: [
new Date('2000-01-01T00:00:00+0100'),
{ date: new Date('2000-01-01T00:00:00+0500') },
Symbol('test'),
true,
],
hash: { '2': 'two', '1': Symbol('one') },
}

expect(new Uniformer().formString(input)).to.equal(
JSON.stringify([
['array', [
'1999-12-31T23:00:00.000Z',
[[ 'date', '1999-12-31T19:00:00.000Z']],
'test',
true
]],
['hash', [['1', 'one'], ['2', 'two']]],
['string', 'a string']
]
));
});
});