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(useTrunc): new function #1838

Merged
merged 8 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
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)))
}