Skip to content

Commit

Permalink
feat(useAbs): new function (#1825)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
LittleSound and antfu committed Jul 17, 2022
1 parent 5e14127 commit 53f4a8a
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/math/useAbs/index.md
@@ -0,0 +1,16 @@
---
category: '@Math'
---

# useAbs

Reactive `Math.abs`.

## Usage

```ts
import { useAbs } from '@vueuse/math'

const value = ref(-23)
const absValue = useAbs(value) // Ref<23>
```
40 changes: 40 additions & 0 deletions packages/math/useAbs/index.test.ts
@@ -0,0 +1,40 @@
import { ref } from 'vue-demi'
import { useAbs } from '.'

describe('useAbs', () => {
test('should be defined', () => {
expect(useAbs).toBeDefined()
})

test('this should work', () => {
const original = ref(-1)
const abs = useAbs(original)

expect(abs.value).toBe(1)

original.value = -23
expect(abs.value).toBe(23)

original.value = 10
expect(abs.value).toBe(10)

original.value = 0
expect(abs.value).toBe(0)
})

test('getter', () => {
const original = ref(-1)
const abs = useAbs(() => original.value)

expect(abs.value).toBe(1)

original.value = -23
expect(abs.value).toBe(23)

original.value = 10
expect(abs.value).toBe(10)

original.value = 0
expect(abs.value).toBe(0)
})
})
13 changes: 13 additions & 0 deletions packages/math/useAbs/index.ts
@@ -0,0 +1,13 @@
import type { MaybeComputedRef } from '@vueuse/shared'
import { resolveUnref } from '@vueuse/shared'
import type { ComputedRef } from 'vue-demi'
import { computed } from 'vue-demi'

/**
* Reactive `Math.abs`.
*
* @see https://vueuse.org/useAbs
*/
export function useAbs(value: MaybeComputedRef<number>): ComputedRef<number> {
return computed(() => Math.abs(resolveUnref(value)))
}

0 comments on commit 53f4a8a

Please sign in to comment.