Skip to content

Commit

Permalink
feat(array): new undot function
Browse files Browse the repository at this point in the history
  • Loading branch information
innocenzi committed Jan 8, 2024
1 parent 136d5fd commit 118ca1f
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 2 deletions.
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

66 changes: 64 additions & 2 deletions src/array.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { flattenArrayable, partition, range, toArray } from './array'
import { describe, expect, expectTypeOf, it } from 'vitest'
import { flattenArrayable, partition, range, toArray, undot } from './array'

describe('toArray', () => {
it.each([
Expand Down Expand Up @@ -73,3 +73,65 @@ it('partition', () => {
),
).toHaveLength(6)
})

describe('undot', () => {
it('should undot keyed collection', () => {
expect(undot({
'name': 'Taylor',
'meta.foo': 'bar',
'meta.baz': ['boom', 'boom', 'boom'],
'meta.bam.boom': 'bip',
})).to.eql({
name: 'Taylor',
meta: {
foo: 'bar',
baz: ['boom', 'boom', 'boom'],
bam: {
boom: 'bip',
},
},
})
})

it('should undot indexed collection', () => {
expect(undot({
'foo.0': 'bar',
'foo.1': 'baz',
'foo.baz': 'boom',
})).to.eql({
foo: {
0: 'bar',
1: 'baz',
baz: 'boom',
},
})
})

it('should undot documentation example', () => {
expect(undot({
'name.first_name': 'Marie',
'name.last_name': 'Valentine',
'address.line_1': '2992 Eagle Drive',
'address.line_2': '',
'address.suburb': 'Detroit',
'address.state': 'MI',
'address.postcode': '48219',
})).to.eql({
name: {
first_name: 'Marie',
last_name: 'Valentine',
},
address: {
line_1: '2992 Eagle Drive',
line_2: '',
suburb: 'Detroit',
state: 'MI',
postcode: '48219',
},
})
})

it('is typed', () => {
expectTypeOf(undot({ 'foo.bar': 'baz' })).toMatchTypeOf<{ foo: { bar: string } }>()
})
})
31 changes: 31 additions & 0 deletions src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,3 +207,34 @@ export function shuffle<T>(array: T[]): T[] {

return array
}

// TODO: types, see @clickbar/dot-diver
/**
* Undots the given object to a nested object.
*/
export function undot<T extends object>(input: T): any {
const result: Record<string, any> = {}

for (const key in input) {
const value = input[key]

if (key.includes('.')) {
const nestedKeys = key.split('.')
let currentLevel = result

for (let i = 0; i < nestedKeys.length; i++) {
const nestedKey = nestedKeys[i]

if (!currentLevel[nestedKey]) {
currentLevel[nestedKey] = i === nestedKeys.length - 1 ? value : {}
}

currentLevel = currentLevel[nestedKey]
}
} else {
result[key] = value
}
}

return result as any
}

0 comments on commit 118ca1f

Please sign in to comment.