Skip to content

Commit

Permalink
feat(kitify): Add assign utility and tests (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
Marinerer authored Dec 23, 2024
1 parent 10cd36d commit 1dcf72a
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
5 changes: 5 additions & 0 deletions libs/kitify/config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export default {
input: 'src/type/isType.ts',
name: 'isType',
},
//==> object
{
input: 'src/object/assign.ts',
name: 'assign',
},
//==> dom
{
input: 'src/dom/detectMouseDirection.ts',
Expand Down
38 changes: 38 additions & 0 deletions libs/kitify/src/object/__tests__/assign.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import assign from '../assign'

describe('assign()', () => {
it('should return an object', () => {
expect(assign({}, {})).toEqual({})
expect(assign({}, {}, {})).toEqual({})
})

it('should return an object with properties from all input objects', () => {
const target = { a: 1 }
const source1 = { b: 2 }
const source2 = { c: 3 }
const result = assign(target, source1, source2)
expect(result).toEqual({ a: 1, b: 2, c: 3 })
})

it('should overwrite properties in target object with properties from input objects', () => {
const target = { a: 1, b: 2 }
const source1 = { b: 3, c: 4 }
const source2 = { c: 5 }
const result = assign(target, source1, source2)
expect(result).toEqual({ a: 1, b: 3, c: 5 })
})

it('should throw an error if target input is undefined or null', () => {
expect(() => assign(undefined as any, { a: 1 })).toThrow(TypeError)
expect(() => assign(null as any, { a: 1 })).toThrow(TypeError)
})

it('should change source object or not', () => {
const target = {}
const source1 = { a: 1 }
expect(assign(target, source1) === target).toBe(true)
expect(assign({}, target, source1) === target).toBe(false)
expect(assign(target, source1) === source1).toBe(false)
expect(assign(target, source1)).toEqual(source1)
})
})
20 changes: 20 additions & 0 deletions libs/kitify/src/object/assign.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
interface Assign {
<T extends {}, U>(target: T, source: U): T & U
<T extends {}, U, V>(target: T, source1: U, source2: V): T & U & V
<T extends {}, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W
}

const assign: Assign =
Object.assign ||
function (target: Record<keyof any, any>, ...sources: any[]) {
for (let i = 1, len = sources.length; i < len; i++) {
const source = sources[i]
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key]
}
}
}
}

export default assign

0 comments on commit 1dcf72a

Please sign in to comment.