Skip to content

Commit

Permalink
feat(useArrayMap): new function (#1908)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
huynl-96 and antfu committed Jul 14, 2022
1 parent 50e3520 commit 4afcb86
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/shared/index.ts
Expand Up @@ -31,6 +31,7 @@ export * from './tryOnMounted'
export * from './tryOnScopeDispose'
export * from './tryOnUnmounted'
export * from './until'
export * from './useArrayMap'
export * from './useArrayFilter'
export * from './useCounter'
export * from './useDateFormat'
Expand Down
36 changes: 36 additions & 0 deletions packages/shared/useArrayMap/index.md
@@ -0,0 +1,36 @@
---
category: Utilities
---

# useArrayMap

Reactive `Array.map`

## Usage

### Use with array of multiple refs

```js
import { useArrayMap } from '@vueuse/core'
const item1 = ref(0)
const item2 = ref(2)
const item3 = ref(4)
const item4 = ref(6)
const item5 = ref(8)
const list = [item1, item2, item3, item4, item5]
const result = useArrayMap(list, i => i * 2)
// result.value: [0, 4, 8, 12, 16]
item2.value = 1
// result.value: [2, 4, 8, 12, 16]
```

### Use with reactive array

```js
import { useArrayMap } from '@vueuse/core'
const list = ref([0, 1, 2, 3, 4])
const result = useArrayMap(list, i => i * 2)
// result.value: [0, 2, 4, 6, 8]
list.value.pop()
// result.value: [0, 2, 4, 6]
```
29 changes: 29 additions & 0 deletions packages/shared/useArrayMap/index.test.ts
@@ -0,0 +1,29 @@
import { ref } from 'vue-demi'
import { useArrayMap } from '../useArrayMap'

describe('useArrayMap', () => {
it('should be defined', () => {
expect(useArrayMap).toBeDefined()
})

it('should work with array of refs', () => {
const item1 = ref(0)
const item2 = ref(2)
const item3 = ref(4)
const item4 = ref(6)
const item5 = ref(8)
const list = [item1, item2, item3, item4, item5]
const result = useArrayMap(list, i => i * 2)
expect(result.value).toStrictEqual([0, 4, 8, 12, 16])
item1.value = 1
expect(result.value).toStrictEqual([2, 4, 8, 12, 16])
})

it('should work with reactive array', () => {
const list = ref([0, 1, 2, 3, 4])
const result = useArrayMap(list, i => i * 2)
expect(result.value).toStrictEqual([0, 2, 4, 6, 8])
list.value.pop()
expect(result.value).toStrictEqual([0, 2, 4, 6])
})
})
11 changes: 11 additions & 0 deletions packages/shared/useArrayMap/index.ts
@@ -0,0 +1,11 @@
import type { MaybeComputedRef } from '@vueuse/shared'
import { resolveUnref } from '@vueuse/shared'
import type { ComputedRef } from 'vue-demi'
import { computed } from 'vue-demi'

export function useArrayMap<T>(
list: MaybeComputedRef<MaybeComputedRef<T>[]>,
fn: (element: T, index: number, array: T[]) => T,
): ComputedRef<T[]> {
return computed(() => resolveUnref(list).map(i => resolveUnref(i)).map(fn))
}

0 comments on commit 4afcb86

Please sign in to comment.