From 85bc226e88b2bec9f56e5b5a3111b385ee4627b6 Mon Sep 17 00:00:00 2001 From: Guotong Liao <37015336+GlintonLiao@users.noreply.github.com> Date: Sat, 15 Oct 2022 07:13:30 -0700 Subject: [PATCH] feat(math): adding several math functions and math test modules (#6) --- src/math/index.ts | 19 +++++++++- test/math.test.ts | 97 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 test/math.test.ts diff --git a/src/math/index.ts b/src/math/index.ts index 1887ed9..33ca982 100644 --- a/src/math/index.ts +++ b/src/math/index.ts @@ -1,4 +1,4 @@ -import { reactify } from '@vueuse/shared' +import { MaybeRef, reactify } from '@vueuse/shared' export * from './generated' @@ -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, b: MaybeRef) => { + return divide(multiply(a, b), gcd(a, b)) +} diff --git a/test/math.test.ts b/test/math.test.ts new file mode 100644 index 0000000..d68ba90 --- /dev/null +++ b/test/math.test.ts @@ -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)) + }) +})