Skip to content

Commit

Permalink
feat: add values
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 21, 2018
1 parent 039d85a commit 549de62
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/forOwn.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import isObject from './isObject'

/**
* 遍历对象的可枚举属性。若回调函数返回 false,遍历会提前退出。
*
Expand All @@ -8,11 +10,13 @@ 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) {
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (callback(obj[key], key as any, obj) === false) {
break
if (isObject(obj)) {
for (const key in obj) {
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (callback(obj[key], key as any, obj) === false) {
break
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ export { default as repeat } from './repeat'
export { default as shuffle } from './shuffle'
export { default as stopEventPropagation } from './stopEventPropagation'
export { default as supportPassiveEventListener } from './supportPassiveEventListener'
export { default as values } from './values'
16 changes: 16 additions & 0 deletions src/values.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import forOwn from './forOwn'

/**
* 返回 obj 自身可枚举属性的值为数组。
*
* @param obj 要检索的对象
* @returns 结果数组
*/
export default function values<
T extends { [key: string]: any },
K extends keyof T
>(obj: T): Array<T[K]> {
const result: Array<T[K]> = []
forOwn(obj, value => result.push(value))
return result
}
16 changes: 16 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -652,3 +652,19 @@ describe('has', () => {
expect(vtils.has(fn, 'y')).toBeFalsy()
})
})

describe('values', () => {
test('对象', () => {
expect(vtils.values({ now })).toEqual([now])
expect(
vtils.values({ 1: 2, x: 'y', t: null, ok: undefined }).sort()
).toEqual(
[2, 'y', null, undefined].sort()
)
})
test('函数', () => {
const fn = () => {}
fn.x = 1
expect(vtils.values(fn)).toEqual([1])
})
})

0 comments on commit 549de62

Please sign in to comment.