Skip to content

Commit

Permalink
feat: add assign
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Feb 19, 2019
1 parent 19e2cb7 commit 151c2b7
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 3 deletions.
18 changes: 18 additions & 0 deletions src/assign.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import forOwn from './forOwn'

/**
* 分配来源对象的可枚举属性到目标对象上。
* 来源对象的应用规则是从左到右,随后的下一个对象的属性会覆盖上一个对象的属性。
*
* @param target 目标对象
* @param sources 来源对象
* @returns 目标对象
*/
export default function assign<T extends Record<string, any>>(target: T, ...sources: any[]): T {
sources.forEach(source => {
forOwn(source, (value, key) => {
target[key] = value
})
})
return target
}
10 changes: 7 additions & 3 deletions src/clamp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@
* @returns 结果值
*/
export default function clamp(value: number, min: number, max: number): number {
return value <= min ? min
: value >= max ? max
: value
return (
value <= min
? min
: value >= max
? max
: value
)
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export { default as Disposer } from './Disposer'
export { default as EventBus } from './EventBus'
export { default as FileData } from './FileData'
export { default as Validator } from './Validator'
export { default as assign } from './assign'
export { default as base64Decode } from './base64Decode'
export { default as base64Encode } from './base64Encode'
export { default as base64UrlDecode } from './base64UrlDecode'
Expand Down
15 changes: 15 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1625,3 +1625,18 @@ describe('column', () => {
})
})
})

describe('assign', () => {
test('ok', () => {
const target = {}
const source1 = { x: 1 }
const source2 = { y: 2 }
expect(vtils.assign(target, source1)).toEqual({ x: 1 })
expect(target).toEqual({ x: 1 })
expect(vtils.assign(source1, source2)).toEqual({ x: 1, y: 2 })
expect(source1).toEqual({ x: 1, y: 2 })
expect(vtils.assign(source2)).toEqual({ y: 2 })
expect(vtils.assign(source2)).toBe(source2)
expect(vtils.assign(source2, undefined)).toBe(source2)
})
})

0 comments on commit 151c2b7

Please sign in to comment.