Skip to content

Commit

Permalink
fix: add sumObjectValues helper and test
Browse files Browse the repository at this point in the history
  • Loading branch information
BRaimbault committed Dec 10, 2024
1 parent dbd09ba commit 245848a
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/util/__tests__/helpers.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { sumObjectValues } from '../helpers.js'

describe('sumObjectValues', () => {
it('should return 0 for an empty object', () => {
expect(sumObjectValues({})).toBe(0)
})

it('should sum flat numeric values in an object', () => {
expect(sumObjectValues({ a: 1, b: 2, c: 3 })).toBe(6)
})

it('should handle nested objects correctly', () => {
const obj = {
a: 1,
b: { c: 2, d: { e: 3 } },
}
expect(sumObjectValues(obj)).toBe(6)
})

it('should ignore non-numeric values', () => {
const obj = {
a: 1,
b: 'string',
c: { d: 2, e: null, f: true },
}
expect(sumObjectValues(obj)).toBe(3)
})

it('should handle an object with only non-numeric values', () => {
const obj = {
a: 'string',
b: null,
c: undefined,
}
expect(sumObjectValues(obj)).toBe(0)
})

it('should handle arrays as object values', () => {
const obj = {
a: [1, 2, 3],
b: { c: [4, 5], d: 6 },
}
expect(sumObjectValues(obj)).toBe(21) // Note: Array elements aren't handled differently, treated as objects.
})
})
13 changes: 13 additions & 0 deletions src/util/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,16 @@ export const getLongestTextLength = (array, key) =>
: text,
''
).length

// Sum all numbers in an object recursively
export const sumObjectValues = (obj) =>
Object.values(obj).reduce((sum, value) => {
if (value === null || value === undefined) {
return sum
} else if (typeof value === 'object') {
return sum + sumObjectValues(value)
} else if (typeof value === 'number') {
return sum + value
}
return sum
}, 0)

0 comments on commit 245848a

Please sign in to comment.