Skip to content

Commit

Permalink
support for adding of partially existing nested keys
Browse files Browse the repository at this point in the history
  • Loading branch information
angryziber committed Aug 17, 2023
1 parent a6ed07c commit b0eb26d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
12 changes: 9 additions & 3 deletions src/common/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {containsHTMLTags, decodeBase64Unicode, deepEqual, encodeBase64Unicode, insertNestedKey, insertKey} from './utils'
import {containsHTMLTags, decodeBase64Unicode, deepEqual, encodeBase64Unicode, insertNestedKey} from './utils'
import {expect} from 'chai'

describe('areObjectsEqual', () => {
Expand Down Expand Up @@ -38,18 +38,24 @@ describe('encode/decodeBase64Unicode', () => {
})
})

describe('insertKey', () => {
describe('insertNestedKey', () => {
it('adds a new key in specified order to an object', () => {
const dict = {x: '1', aa: '10', v: '3'}
insertNestedKey(dict, 'z', 1)
expect(JSON.stringify(dict)).to.eq(`{"x":"1","aa":"10","z":"","v":"3"}`)
})

it('adds a new deep key, separated by dots', () => {
it('adds a new nested key, separated by dots', () => {
const dict = {x: '1', aa: '10', v: '3'}
insertNestedKey(dict, 'hello.world.baz', 1)
expect(JSON.stringify(dict)).to.eq(`{"x":"1","aa":"10","hello":{"world":{"baz":""}},"v":"3"}`)
})

it('adds a new deep key to existing sub keys', () => {
const dict = {x: {y: {z: '1'}}}
insertNestedKey(dict, 'x.y.zz', 1)
expect(JSON.stringify(dict)).to.eq(`{"x":{"y":{"z":"1","zz":""}}}`)
})
})

describe('containsHTMLTags', () => {
Expand Down
9 changes: 8 additions & 1 deletion src/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function deepEqual(a: Record<string, any>, b: Record<string, any>): boole
return JSON.stringify(a) == JSON.stringify(b)
}

export function insertKey(dict: Dict, key: string, afterPos: number, value: string|object = '') {
function insertKey(dict: Dict, key: string, afterPos: number, value: string|object = '') {
Object.assign(dict, Object.entries(dict).reduce((d: Dict, [k,v], i) => {
delete dict[k]
d[k] = v
Expand All @@ -31,6 +31,13 @@ export function insertKey(dict: Dict, key: string, afterPos: number, value: stri

export function insertNestedKey(dict: Dict, deepKey: string, afterPos: number) {
const keys = deepKey.split('.')
for (let key of [...keys]) {
if (dict[key]) {
dict = dict[key]
keys.shift()
afterPos = Object.keys(dict).length - 1
} else break
}
let value: string|Dict = ''
if (keys.length > 1) {
let target: Dict = value = {}
Expand Down

0 comments on commit b0eb26d

Please sign in to comment.