Skip to content

Commit

Permalink
feat: add set
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Nov 8, 2018
1 parent 96b3fbd commit 8bb14d3
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export { default as reduce } from './reduce'
export { default as repeat } from './repeat'
export { default as request } from './request'
export { default as result } from './result'
export { default as set } from './set'
export { default as shuffle } from './shuffle'
export { default as startsWith } from './startsWith'
export { default as stopEventPropagation } from './stopEventPropagation'
Expand Down
22 changes: 22 additions & 0 deletions src/set.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import has from './has'
import isObject from './isObject'
import toPath from './toPath'

/**
* 根据 obj 对象的路径 path 设置值。
*
* @param obj 要检索的对象
* @param path 属性路径
* @param value 要设置的值
*/
export default function set(obj: object, path: string | string[], value: any): void {
path = Array.isArray(path) ? path : toPath(path)
let last: any = obj
for (let i = 0, len = path.length; i < len; i++) {
if (i === len - 1) {
last[path[i]] = value
} else {
last = last[path[i]] = isObject(last[path[i]]) ? last[path[i]] : {}
}
}
}
34 changes: 34 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1237,3 +1237,37 @@ describe('get', () => {
expect(vtils.get(obj, '1.2')).toBe(undefined)
})
})

describe('set', () => {
test('ok', () => {
const fn = () => {}
const obj: any = {
x: 1,
y: [1, 2, { z: null }],
z: { we: 'hello' },
'1.2': 1.2,
fn
}
vtils.set(obj, 'x', 2)
vtils.set(obj, 'y[1]', '88')
vtils.set(obj, 'y[2].z', [9])
vtils.set(obj, 'z.we', {})
vtils.set(obj, 'z.we[1]', null)
vtils.set(obj, 'z.we[1].xxx', undefined)
vtils.set(obj, 'yyy', '?')
vtils.set(obj, '[1.2]', [])
vtils.set(obj, '1.2', ' ')
vtils.set(obj, 'fn.hello', 'world')
expect(obj).toEqual({
x: 2,
y: [1, '88', { z: [9] }],
z: { we: { 1: { xxx: undefined } } },
yyy: '?',
'1.2': [],
1: {
2: ' '
},
fn
})
})
})

0 comments on commit 8bb14d3

Please sign in to comment.