Skip to content

Commit

Permalink
feat(useTrunc): new function (#1838)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
hanpei and antfu committed Jul 17, 2022
1 parent 0acd20c commit d5717bd
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/math/index.ts
Expand Up @@ -14,3 +14,4 @@ export * from './useMin'
export * from './useProjection'
export * from './useRound'
export * from './useSum'
export * from './useTrunc'
18 changes: 18 additions & 0 deletions packages/math/useTrunc/index.md
@@ -0,0 +1,18 @@
---
category: '@Math'
---

# useTrunc

Reactive `Math.trunc`.

## Usage

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

const value1 = ref(0.95)
const value2 = ref(-2.34)
const result1 = useTrunc(value1) // 0
const result2 = useTrunc(value2) // -2
```
44 changes: 44 additions & 0 deletions packages/math/useTrunc/index.test.ts
@@ -0,0 +1,44 @@
import { ref } from 'vue-demi'
import { useTrunc } from '.'

// Returns:
// 0 -> 0
// -0 -> -0
// 0.2 -> 0
// -0.2 -> -0
// 0.7 -> 0
// -0.7 -> -0
// Infinity -> Infinity
// -Infinity -> -Infinity
// NaN -> NaN
// null -> 0

describe('useTrunk', () => {
it('should be defined', () => {
expect(useTrunc).toBeDefined()
})
it('should work', () => {
const base = ref(1.95)
const result = useTrunc(base)
expect(result.value).toBe(1)
base.value = -7.004
expect(result.value).toBe(-7)

base.value = 0
expect(result.value).toBe(0)
base.value = -0
expect(result.value).toBe(-0)

base.value = 0.2
expect(result.value).toBe(0)
base.value = -0.2
expect(result.value).toBe(-0)

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

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

0 comments on commit d5717bd

Please sign in to comment.