Skip to content

Commit

Permalink
Created depth map util tests
Browse files Browse the repository at this point in the history
createDepthMap excludes rows that does not have selectionKey field present (the primary key)
  • Loading branch information
underfisk committed Mar 18, 2021
1 parent 0cfadf3 commit b72ab88
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 6 deletions.
68 changes: 68 additions & 0 deletions src/nestedRows/__tests__/createDepthMap.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { createDepthMap } from '../createDepthMap'
import { Row } from '../../types'
import { DepthMap } from '../depth-map.interface'

describe('createDepthMap', () => {
it('should return empty', () => {
expect(createDepthMap([], 'id')).toEqual({})
})

it('should return empty if selectionKey does not find the row', () => {
const rows: Row[] = [{
id: '1234',
}]
expect(createDepthMap(rows, 'nonexistingid')).toEqual({})
})

it('should return only one row if it contains a valid selectionKey field', () => {
const rows: Row[] = [{
id: '1234',
}, {
_id: '555'
}]
expect(createDepthMap(rows, '_id')).toEqual({ "555": 1 })
})

it('should create correctly the depths', () => {
const rows: Row[] = [{
id: '1',
__children: [{
id: '11',
__children: [{
id: '111'
}]
}]
}, {
id: '2',
__children: [{
id: '22'
}]
}]
const expected: DepthMap = {
1: 1,
11: 2,
111: 3,
2: 1,
22: 2
}
expect(createDepthMap(rows, 'id')).toEqual(expected)
})

it('should use a default depth if passed', () => {
const rows: Row[] = [{
id: 1
}]
expect(createDepthMap(rows, 'id', 5)).toEqual({ 1: 5 })
})

it('should use a default depth map if provided', () => {
const rows: Row[] = [{
id: 1
}]
const expected: DepthMap = {
22: 50,
1: 1
}
expect(createDepthMap(rows, 'id', 1, { 22: 50 })).toEqual(expected)
})
})
16 changes: 10 additions & 6 deletions src/nestedRows/createDepthMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { DepthMap } from './depth-map.interface'
* Recursively creates a map with the row ids -> depth level
* @param rows
* @param selectionKey
* @param depth
* @param map
* @param depth If provided will be used as the 0-th level depth
* @param map If a map is provided by default it will be mutated so make sure you create a
* new copy of it in case you want to avoid mutation
*/
export const createDepthMap = (
rows: Row[],
Expand All @@ -15,10 +16,13 @@ export const createDepthMap = (
map = {} as DepthMap,
): DepthMap => {
rows.forEach(e => {
// eslint-disable-next-line no-param-reassign
map[e[selectionKey]] = depth
if (e.__children) {
createDepthMap(e.__children, selectionKey, depth + 1, map)
const id = e[selectionKey]
if (id) {
// eslint-disable-next-line no-param-reassign
map[id] = depth
if (e.__children) {
createDepthMap(e.__children, selectionKey, depth + 1, map)
}
}
})

Expand Down

0 comments on commit b72ab88

Please sign in to comment.