Skip to content

Commit

Permalink
common: add depthOf() function
Browse files Browse the repository at this point in the history
  • Loading branch information
arobsn committed Aug 6, 2023
1 parent c1ef9d2 commit 9bd393b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/tall-tips-shake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fleet-sdk/common": minor
---

Add `depthOf()` function.
16 changes: 16 additions & 0 deletions packages/common/src/utils/array.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
areEqualBy,
at,
chunk,
depthOf,
endsWith,
first,
hasDuplicates,
Expand Down Expand Up @@ -397,3 +398,18 @@ describe("uniqBy()", () => {
).to.be.true;
});
});

describe("depthOf()", () => {
it("Should count depth of arrays", () => {
expect(depthOf([])).to.be.equal(1);
expect(depthOf([[]])).to.be.equal(2);
expect(depthOf([[[], []]])).to.be.equal(3);
expect(depthOf([[[[], [], []]]])).to.be.equal(4);
expect(depthOf([[[[], [[[]]]]]])).to.be.equal(6);

expect(depthOf({})).to.be.equal(0);
expect(depthOf(1)).to.be.equal(0);
expect(depthOf(undefined)).to.be.equal(0);
expect(depthOf(null)).to.be.equal(0);
});
});
4 changes: 4 additions & 0 deletions packages/common/src/utils/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,7 @@ export function uniqBy<T>(
.values()
);
}

export function depthOf(array: unknown | unknown[]): number {
return Array.isArray(array) ? 1 + Math.max(0, ...array.map(depthOf)) : 0;
}

0 comments on commit 9bd393b

Please sign in to comment.