Skip to content

Commit

Permalink
chore: format
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jul 19, 2024
1 parent b3eef45 commit ee3aac3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 31 deletions.
50 changes: 26 additions & 24 deletions src/object/crush.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isDate, isPrimitive, objectify } from "radashi";
import { isDate, isPrimitive, objectify } from 'radashi'

/**
* Flattens a deep object to a single dimension, converting the keys
Expand All @@ -12,34 +12,36 @@ import { isDate, isPrimitive, objectify } from "radashi";
* ```
*/
type Primitive =
| number
| string
| boolean
| Date
| symbol
| bigint
| undefined
| null;
| number
| string
| boolean
| Date
| symbol
| bigint
| undefined
| null

const crushToPvArray: (
obj: object,
path: string,
obj: object,
path: string,
) => Array<{ p: string; v: Primitive }> = (obj: object, path: string) =>
Object.entries(obj).flatMap(([key, value]) =>
isPrimitive(value) || isDate(value)
? { p: path === "" ? key : `${path}.${key}`, v: value }
: crushToPvArray(value, path === "" ? key : `${path}.${key}`),
);
Object.entries(obj).flatMap(([key, value]) =>
isPrimitive(value) || isDate(value)
? { p: path === '' ? key : `${path}.${key}`, v: value }
: crushToPvArray(value, path === '' ? key : `${path}.${key}`),
)

export function crush<TValue extends object>(
value: TValue,
value: TValue,
): Record<string, Primitive> | Record<string, never> {
if (!value) return {};
if (!value) {
return {}
}

const result = objectify(
crushToPvArray(value, ""),
(o) => o.p,
(o) => o.v,
);
return result;
const result = objectify(
crushToPvArray(value, ''),
o => o.p,
o => o.v,
)
return result
}
14 changes: 7 additions & 7 deletions tests/object/crush.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,34 +35,34 @@ describe('crush', () => {
})
test('handles property names with dots 1', () => {
const obj = {
a: { 'b.c': 'value' }
a: { 'b.c': 'value' },
}
expect(_.crush(obj)).toEqual({
'a.b.c': 'value'
'a.b.c': 'value',
})
})
test('handles property names with dots 2', () => {
const obj = {
'a.b': { c: 'value' }
'a.b': { c: 'value' },
}
expect(_.crush(obj)).toEqual({
'a.b.c': 'value'
'a.b.c': 'value',
})
})
test('handles property names with dots 3', () => {
const obj = {
'a.b': { 'c.d': 123.4 }
'a.b': { 'c.d': 123.4 },
}
expect(_.crush(obj)).toEqual({
'a.b.c.d': 123.4
'a.b.c.d': 123.4,
})
})
test('handles arrays', () => {
const obj = ['value', 123.4, true]
expect(_.crush(obj)).toEqual({
'0': 'value',
'1': 123.4,
'2': true
'2': true,
})
})
})

0 comments on commit ee3aac3

Please sign in to comment.