Skip to content

Commit

Permalink
feat(array): 新增chunk,compact,head,first,last,flattenDepth,flattenDeep…
Browse files Browse the repository at this point in the history
…,flatten
  • Loading branch information
vfiee committed Apr 2, 2022
1 parent d97d81c commit 198abc1
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 2 deletions.
3 changes: 3 additions & 0 deletions packages/array/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,8 @@
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
},
"dependencies": {
"@v-utils/type": "workspace:^0.0.1"
}
}
44 changes: 43 additions & 1 deletion packages/array/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,52 @@
/*
* @Author: vyron
* @Date: 2022-03-24 14:48:36
* @LastEditTime: 2022-03-24 14:48:37
* @LastEditTime: 2022-04-01 15:44:39
* @LastEditors: vyron
* @Description: 数组常用方法
* @FilePath: /v-utils/packages/array/src/index.ts
*/

// 判断是否为数组
export const isArray = Array.isArray

// 将数组拆分成多个长度为 size 的块,并将多个块组成一个新数组并返回;
// 如果 array 无法被分割成全部等长的块,剩余的元素将组成一个块
export const chunk = (array: any[], size: number = 1) => {
const result: any[] = []
let index = 0
while (index < array.length) {
result.push(array.slice(index, index + size))
index += size
}
return result
}

// 过滤并返回数组中所有的 truthy 值元素
export const compact = (array: any[]) => array.filter(Boolean)

// 返回数组的第一个元素,如果没有则返回 undefined
export const head = (array: any[]) => (isArray(array) ? array[0] : undefined)

export const first = head

// 返回数组的最后一个元素,如果没有则返回 undefined
export const last = (array: any[]) =>
isArray(array) ? array[array.length - 1] : undefined

// 根据 depth 递归减少 array 的嵌套层级
export const flattenDepth = (array: any[], depth = 1): any[] => {
if (!isArray(array) || depth < 1) return array
return array.reduce((acc, val) => {
if (isArray(val)) {
return acc.concat(flattenDepth(val, depth - 1))
}
return acc.concat(val)
}, [])
}

// 将数组递归为一维数组
export const flattenDeep = (array: any[]) => flattenDepth(array, array.length)

// 减少一级数组的嵌套
export const flatten = (array: any[]) => flattenDepth(array)
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pnpm-workspace.yaml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
packages:
- 'packages:/**'
- 'packages/**'

0 comments on commit 198abc1

Please sign in to comment.