Skip to content

Commit

Permalink
chore: add stringify fn
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Jan 7, 2024
1 parent dc6b57e commit 04c970f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { describe, it, expect } from 'vitest'
import { stringifyFlatObject } from './utils'

describe('utils', () => {
describe('stringifyFlatObject', () => {
it('stringifies an object no matter the order of keys', () => {
expect(stringifyFlatObject({ a: 1, b: 2 })).toBe('{"a":1,"b":2}')
expect(stringifyFlatObject({ b: 2, a: 1 })).toBe('{"a":1,"b":2}')
})

it('works with all primitives', () => {
expect(stringifyFlatObject({ a: 1, b: 2 })).toBe('{"a":1,"b":2}')
expect(stringifyFlatObject({ a: '1', b: '2' })).toBe('{"a":"1","b":"2"}')
expect(stringifyFlatObject({ a: true, b: false })).toBe(
'{"a":true,"b":false}'
)
expect(stringifyFlatObject({ a: null })).toBe('{"a":null}')
})

it('works with arrays', () => {
expect(stringifyFlatObject({ a: [1, 2], b: [3, 4] })).toBe(
'{"a":[1,2],"b":[3,4]}'
)
expect(stringifyFlatObject({ b: [1, 2], a: [3, 4] })).toBe(
'{"a":[3,4],"b":[1,2]}'
)
})
})
})
16 changes: 16 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,19 @@ export type _MaybeArray<T> = T | T[]
*/
export const toArray = <T>(value: _MaybeArray<T>): T[] =>
Array.isArray(value) ? value : [value]

type _JSONPrimitive = string | number | boolean | null

export interface _Object {
[key: string]: _JSONPrimitive | Array<_JSONPrimitive>
}

/**
* Stringifies an object no matter the order of keys. This is used to create a hash for a given object. It only works
* with flat objects. It can contain arrays of primitives only.
*
* @param obj - object to stringify
*/
export function stringifyFlatObject(obj: _Object): string {
return JSON.stringify(obj, Object.keys(obj).sort())
}

0 comments on commit 04c970f

Please sign in to comment.