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(useArrayIncludes): new function #2708

Merged
merged 12 commits into from
Mar 4, 2023
Merged
1 change: 1 addition & 0 deletions packages/shared/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export * from './useArrayEvery'
export * from './useArrayFilter'
export * from './useArrayFind'
export * from './useArrayFindIndex'
export * from './useArrayIncludes'
export * from './useArrayJoin'
export * from './useArrayMap'
export * from './useArrayReduce'
Expand Down
22 changes: 22 additions & 0 deletions packages/shared/useArrayIncludes/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
category: Array
---

# useArrayIncludes

Reactive `Array.includes`

## Usage

### Use with reactive array

```js
import { useArrayIncludes } from '@vueuse/core'
const list = ref([0, 2, 4, 6, 8])
const result = useArrayIncludes(list, 10)
// result.value: false
list.value.push(10)
// result.value: true
list.value.pop()
// result.value: false
```
18 changes: 18 additions & 0 deletions packages/shared/useArrayIncludes/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { ref } from 'vue-demi'
import { useArrayIncludes } from './index'

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

it('should work with array of refs', () => {
const array = ref([0, 2, 4, 6])
const result = useArrayIncludes(array, 8)
expect(result.value).toBeFalsy()
array.value.push(8)
expect(result.value).toBeTruthy()
array.value.pop()
expect(result.value).toBeFalsy()
})
})
20 changes: 20 additions & 0 deletions packages/shared/useArrayIncludes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import type { ComputedRef } from 'vue-demi'
import { computed } from 'vue-demi'
import type { MaybeComputedRef } from '../utils'
import { resolveUnref } from '../resolveUnref'

/**
* Reactive `Array.includes`
*
* @see https://vueuse.org/useArrayIncludes
* @param {Array} list - the array was called upon.
* @param searchElement - the value to search for.
*
* @returns {boolean} true if the `searchElement` is found in the array. Otherwise, false.
*/
export function useArrayIncludes<T>(
list: MaybeComputedRef<MaybeComputedRef<T>[]>,
searchElement: T,
): ComputedRef<boolean> {
return computed(() => resolveUnref(list).includes(searchElement))
}