Skip to content

Commit

Permalink
feat(useArrayFind): new function (#1875)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
yjl9903 and antfu committed Jul 17, 2022
1 parent 578460b commit d00b7ed
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
29 changes: 29 additions & 0 deletions packages/shared/useArrayFind/index.md
@@ -0,0 +1,29 @@
---
category: Array
---

# useArrayFind

Reactive `Array.find`.

## Usage

```js
import { useArrayFind } from '@vueuse/core'

const list = [ref(1), ref(-1), ref(2)]
const positive = useArrayFind(list, val => val > 0)
// positive.value: 1
```

### Use with reactive array

```js
import { useArrayFind } from '@vueuse/core'

const list = reactive([-1, -2])
const positive = useArrayFind(list, val => val > 0)
// positive.value: undefined
list.push(1)
// positive.value: 1
```
35 changes: 35 additions & 0 deletions packages/shared/useArrayFind/index.test.ts
@@ -0,0 +1,35 @@
import { reactive, ref } from 'vue-demi'
import { useSetup } from '../../.test'
import { useArrayFind } from '../useArrayFind'

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

it('should find postive', () => {
useSetup(() => {
const item1 = ref(1)
const item2 = ref(2)
const item3 = ref(3)
const positive = useArrayFind([item1, item2, item3], val => val > 0)
expect(positive.value).toBe(1)
item1.value = -1
expect(positive.value).toBe(2)
item2.value = -1
expect(positive.value).toBe(3)
item3.value = -1
expect(positive.value).toBe(undefined)
})
})

it('should work with reactive array', () => {
useSetup(() => {
const list = reactive([-1, -2])
const positive = useArrayFind(list, val => val > 0)
expect(positive.value).toBe(undefined)
list.push(1)
expect(positive.value).toBe(1)
})
})
})
16 changes: 16 additions & 0 deletions packages/shared/useArrayFind/index.ts
@@ -0,0 +1,16 @@
import type { MaybeComputedRef } from '@vueuse/shared'
import type { ComputedRef } from 'vue-demi'
import { resolveUnref } from '@vueuse/shared'
import { computed } from 'vue-demi'

export function useArrayFind<T>(
list: MaybeComputedRef<MaybeComputedRef<T>[]>,
fn: (element: T, index: number, array: MaybeComputedRef<T>[]) => boolean,
): ComputedRef<T | undefined> {
return computed(() =>
resolveUnref<T | undefined>(
resolveUnref(list)
.find((element, index, array) => fn(resolveUnref(element), index, array)),
),
)
}

0 comments on commit d00b7ed

Please sign in to comment.