Skip to content
This repository has been archived by the owner on Dec 24, 2022. It is now read-only.

Commit

Permalink
Add objectSize utility method
Browse files Browse the repository at this point in the history
Calculates number of primitives in an object (leaf nodes)

Signed-off-by: Brian Evans <[email protected]>
  • Loading branch information
mrbrianevans committed Nov 6, 2021
1 parent 278f32c commit 10837b0
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
41 changes: 41 additions & 0 deletions lib-testing/test/common/ArrayUtils/ObjectSize.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { objectSize } from '../../../../lib/common/ArrayUtils'
import * as Assert from 'assert'

describe('calculate the size of an object in number of primitives', function () {
it('should get the size of a simple object', function () {
const obj = {
action: 'delete',
date: new Date().getTime()
}
const output = objectSize(obj)
Assert.equal(output, 2)
})
it('should get the size of an object with 5 primitives', function () {
const obj = {
action: 'delete',
date: { year: 2020, month: 10 },
permission: true,
role: 'Admin'
}
const output = objectSize(obj)
Assert.equal(output, 5)
})
it('should get the size of an object with 6 primitives including null', function () {
const obj = {
action: 'delete',
date: { year: 2020, month: 10 },
permission: true,
role: 'Admin',
violation: null
}
const output = objectSize(obj)
Assert.equal(output, 6)
})
it('should get the size of an object with 6 primitives in an array', function () {
const obj = {
actions: ['create', 'delete', 'update', 'replace', 'rename', 'edit']
}
const output = objectSize(obj)
Assert.equal(output, 6)
})
})
13 changes: 13 additions & 0 deletions lib/common/ArrayUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,16 @@ export const repeat = <T = any>(
): T[] => {
return range(qty).map((v, i) => mapFn(i))
}

/**
* Returns the number of primitives in an object
*/
export const objectSize = (object: any) => {
if (typeof object !== 'object' || object === null) {
return 1
} else
return Object.values(object).reduce(
(total, current) => objectSize(current) + total,
0
)
}

0 comments on commit 10837b0

Please sign in to comment.