Skip to content

Commit

Permalink
feat: new function - sum
Browse files Browse the repository at this point in the history
  • Loading branch information
GreatAuk committed Apr 30, 2024
1 parent 094e295 commit 4842a86
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
7 changes: 6 additions & 1 deletion packages/core/src/math.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { average, toFixedWithoutZeros } from './math'
import { average, toFixedWithoutZeros, sum } from './math'

describe('math functions', () => {
it('toFixedWithoutZeros', () => {
Expand All @@ -11,4 +11,9 @@ describe('math functions', () => {
expect(average(...[1, 2, 3])).toBe(2)
expect(average(...[])).toBe(NaN)
})
it('sum', () => {
expect(sum(1, 2, 3)).toBe(6)
expect(sum(1, 2, 3, 4)).toBe(10)
expect(sum(...[])).toBe(0)
})
})
21 changes: 20 additions & 1 deletion packages/core/src/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
* @param precision
* @returns
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/math.ts
* @example
* ```ts
* toFixedWithoutZeros(1.2345, 2) // '1.23'
* toFixedWithoutZeros(1.2000, 2) // '1.2'
* ```
*/
export function toFixedWithoutZeros(num: number, precision: number): string {
return `${Number(num.toFixed(precision))}`
Expand All @@ -12,7 +17,7 @@ export function toFixedWithoutZeros(num: number, precision: number): string {
/**
* get the average of all the numbers passed in
* @example
* ```
* ```ts
* average(1, 2, 3) // 2
* average(...[1, 2, 3]) // 2
* ```
Expand All @@ -21,3 +26,17 @@ export function toFixedWithoutZeros(num: number, precision: number): string {
export function average(...args: number[]): number {
return args.reduce((a, b) => a + b, 0) / args.length
}

/**
* Calculates the sum of the given numbers.
* @param args - The numbers to be summed.
* @returns The sum of the numbers.
* @example
* ```ts
* sum(1, 2, 3) // 6
* sum(1, 2, 3, 4) // 10
* ```
*/
export function sum(...args: number[]): number {
return args.reduce((a, b) => a + b, 0)
}

0 comments on commit 4842a86

Please sign in to comment.