Skip to content

Commit

Permalink
feat: add column
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Feb 15, 2019
1 parent fcaf328 commit 329fd9f
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/column.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* 返回对象数组中指定的一列。
*
* @param arr 要操作的对象数组
* @param columnKey 列的键值
* @param [indexKey] 作为返回对象的键的列,若不设置,则返回数组
* @returns 列对象或数组
*/
export default function column<
O extends Record<string, any>,
CK extends keyof O,
IK extends keyof O,
>(
arr: O[],
columnKey: CK,
indexKey?: IK
): IK extends undefined ? Array<O[CK]> : Record<O[IK], O[CK]> {
return arr.reduce<any>(
(res, item, index) => {
res[indexKey ? item[indexKey] : index] = item[columnKey]
return res
},
indexKey ? {} : []
)
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export { default as bindEvent } from './bindEvent'
export { default as castArray } from './castArray'
export { default as chunk } from './chunk'
export { default as clamp } from './clamp'
export { default as column } from './column'
export { default as compareVersion } from './compareVersion'
export { default as defaultValue } from './defaultValue'
export { default as endsWith } from './endsWith'
Expand Down
17 changes: 17 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1608,3 +1608,20 @@ describe('compareVersion', () => {
expect(vtils.compareVersion('10.1.1-alpha2', '10.1.1-alpha5')).toEqual(-1)
})
})

describe('column', () => {
test('ok', () => {
const records = [
{ id: 1, name: 'Jay', age: 20 },
{ id: 2, name: 'Baby', age: 1 },
{ id: 5, name: 'Yoyo', age: 100 },
]
expect(vtils.column(records, 'id')).toEqual([1, 2, 5])
expect(vtils.column(records, 'name')).toEqual(['Jay', 'Baby', 'Yoyo'])
expect(vtils.column(records, 'name', 'id')).toEqual({
1: 'Jay',
2: 'Baby',
5: 'Yoyo',
})
})
})

0 comments on commit 329fd9f

Please sign in to comment.