Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useArrayFind): new function #1875

Merged
merged 3 commits into from Jul 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)),
),
)
}