Skip to content

Commit

Permalink
feat(useArrayEvery): new function
Browse files Browse the repository at this point in the history
  • Loading branch information
huynl-96 committed Jul 14, 2022
1 parent 606cd26 commit f074b63
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 './useArrayEvery'
export * from './useCounter'
export * from './useDateFormat'
export * from './useDebounceFn'
Expand Down
36 changes: 36 additions & 0 deletions packages/shared/useArrayEvery/index.md
@@ -0,0 +1,36 @@
---
category: Utilities
---

# useArrayEvery

Reactive `Array.every`

## Usage

### Use with array of multiple refs

```js
import { useArrayEvery } 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 = useArrayEvery(list, i => i % 2 === 0)
// result.value: true
item1.value = 1
// result.value: false
```

### Use with reactive array

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

describe('useArrayEvery', () => {
it('should be defined', () => {
expect(useArrayEvery).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 = useArrayEvery(list, i => i % 2 === 0)
expect(result.value).toBe(true)
item1.value = 1
expect(result.value).toBe(false)
})

it('should work with reactive array', () => {
const list = ref([0, 2, 4, 6, 8])
const result = useArrayEvery(list, i => i % 2 === 0)
expect(result.value).toBe(true)
list.value.push(9)
expect(result.value).toBe(false)
})
})
11 changes: 11 additions & 0 deletions packages/shared/useArrayEvery/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 useArrayEvery<T>(
list: MaybeComputedRef<MaybeComputedRef<T>[]>,
fn: (element: T, index: number, array: T[]) => boolean,
): ComputedRef<boolean> {
return computed(() => resolveUnref(list).map(i => resolveUnref(i)).every(fn))
}

0 comments on commit f074b63

Please sign in to comment.