Skip to content

Commit

Permalink
feat(math): adding several math functions and math test modules (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
GlintonLiao authored Oct 15, 2022
1 parent 1dcb49a commit 85bc226
Show file tree
Hide file tree
Showing 2 changed files with 115 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/math/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { reactify } from '@vueuse/shared'
import { MaybeRef, reactify } from '@vueuse/shared'

export * from './generated'

Expand All @@ -24,3 +24,20 @@ export const divide = reactify((a: number, b: number) => a / b)

/*@__PURE__*/
export const subtract = reactify((a: number, b: number) => a - b)

/*@__PURE__*/
export const mod = reactify((a: number, b: number) => a % b)

/*@__PURE__*/
const pureGcd = (a: number, b: number): number => {
if (b === 0) return a
else return pureGcd(b, a % b)
}

/*@__PURE__*/
export const gcd = reactify(pureGcd)

/*@__PURE__*/
export const lcm = (a: MaybeRef<number>, b: MaybeRef<number>) => {
return divide(multiply(a, b), gcd(a, b))
}
97 changes: 97 additions & 0 deletions test/math.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { ref } from 'vue-demi'
import { is, set, negative, sum, multiply, divide, subtract, mod, gcd, lcm } from '../src'
import { $expect } from './utils'

describe('reactiveMath', () => {
it('negative', () => {
const a = ref(9)
const c = negative(a)
$expect(is(c, -9))
$expect(is(a, 9))

set(a, 10)
$expect(is(c, -10))
})

it('sum', () => {
const a = ref(1)
const b = ref(2)
const c = ref(3)
const d = sum(a, b, c)
$expect(is(d, 6))

set(a, 10)
set(b, 15)
$expect(is(d, 28))
})

it('subtract', () => {
const a = ref(1)
const b = ref(2)
const c = subtract(a, b)
$expect(is(c, -1))

set(a, 20)
set(b, 15)
$expect(is(c, 5))
})

it('multiply', () => {
const a = ref(1)
const b = ref(2)
const c = ref(3)
const d = multiply(a, b, c)
$expect(is(d, 6))

set(a, 4)
set(b, 5)
$expect(is(d, 60))
})

it('divide', () => {
const a = ref(1)
const b = ref(2)
const c = divide(a, b)
$expect(is(c, 0.5))

set(a, 20)
set(b, 10)
$expect(is(c, 2))
})

it('mod', () => {
const a = ref(15)
const b = ref(9)
const c = mod(a, b)
$expect(is(c, 6))
$expect(is(b, 9))

set(a, 3)
set(b, 2)
$expect(is(c, 1))
})

it('gcd', () => {
const a = ref(9)
const b = ref(15)
const c = gcd(a, b)
$expect(is(c, 3))
$expect(is(a, 9))

set(a, 14)
set(b, 21)
$expect(is(c, 7))
$expect(is(a, 14))
})

it('lcm', () => {
const a = ref(2)
const b = ref(3)
const c = lcm(a, b)
$expect(is(c, 6))

set(a, 7)
set(b, 14)
$expect(is(c, 14))
})
})

0 comments on commit 85bc226

Please sign in to comment.