Skip to content

Commit

Permalink
feat: add forOwn
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 10, 2018
1 parent aae5a9b commit b9c5823
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/forOwn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* 遍历对象的可枚举属性。若回调函数返回 false,遍历会提前退出。
*
* @param obj 要遍历的对象
* @param callback 回调函数
*/
export default function forOwn<
T extends { [key: string]: any },
K extends keyof T
>(obj: T, callback: (value: T[K], key: K, obj: T) => any): void {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (callback(obj[key], key as any, obj) === false) {
break
}
}
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export { default as bindEvent } from './bindEvent'
export { default as castArray } from './castArray'
export { default as clamp } from './clamp'
export { default as Disposer } from './Disposer'
export { default as forOwn } from './forOwn'
export { default as inBrowser } from './inBrowser'
export { default as isFunction } from './isFunction'
export { default as isNil } from './isNil'
Expand Down
30 changes: 30 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,33 @@ describe('isNil', () => {
expect(vtils.isNil(/X/)).toBeFalsy()
})
})

describe('forOwn', () => {
test('普通对象', () => {
const arr: Array<[any, any]> = []
vtils.forOwn({ x: 1, y: 2, 3: 3 }, (value, key) => {
arr.push([key, value])
})
expect(arr).toContainEqual(['y', 2])
expect(arr).toContainEqual(['x', 1])
expect(arr).toContainEqual(['3', 3])
})
test('Object.create(null)', () => {
const obj: { [key: string]: number } = Object.create(null)
obj.x = 1
obj.y = 2
const arr: Array<[any, any]> = []
vtils.forOwn(obj, (value, key) => {
arr.push([key, value])
})
expect(arr).toContainEqual(['y', 2])
expect(arr).toContainEqual(['x', 1])
})
test('返回 false 退出遍历', () => {
const arr: Array<[any, any]> = []
vtils.forOwn({ x: 1, y: 2, 3: 3 }, (value, key) => {
return false
})
expect(arr).toEqual([])
})
})

0 comments on commit b9c5823

Please sign in to comment.