Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add unit tests for collection utils #2564

Merged
merged 3 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions packages/xrpl/src/utils/collections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,24 @@ type ValueOf<T> = T[keyof T]
*/
export function groupBy<T>(
array: T[],
iteratee: (value: T, index: number, array: T[]) => string,
): { [p: string]: T[] } {
iteratee: (value: T, index: number, array: T[]) => string | number,
): Record<string | number, T[]> {
// eslint-disable-next-line max-params -- need all the params for the fallback
return array.reduce<{ [key: string]: T[] }>(function predicate(
acc,
value,
index,
arrayReference,
) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- being safe for js users
;(acc[iteratee(value, index, arrayReference)] ||= []).push(value)
function predicate(
acc: Record<string | number, T[]>,
value: T,
index: number,
arrayReference: T[],
): Record<string | number, T[]> {
const key = iteratee(value, index, arrayReference) || 0
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Find existing group or create a new one
const group = acc[key] || []
group.push(value)
acc[key] = group
return acc
},
{})
}

return array.reduce(predicate, {})
}

/**
Expand Down
27 changes: 27 additions & 0 deletions packages/xrpl/test/utils/collections.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { groupBy, omitBy } from '../../src/utils/collections'

describe('Collection Utils:', () => {
// Inspired from tests at https://github.com/lodash/lodash/blob/main/test/groupBy.spec.js
describe('groupBy', () => {
const array = [6.1, 4.2, 6.3]

it('should transform keys by `iteratee`', () => {
const actual = groupBy(array, Math.floor)
expect(actual).toEqual({ 4: [4.2], 6: [6.1, 6.3] })
})

it('should transform keys by `iteratee` that returns strings', () => {
const actual = groupBy(array, (item) => Math.floor(item).toString())
expect(actual).toEqual({ '4': [4.2], '6': [6.1, 6.3] })
})
})

// Taken from https://github.com/lodash/lodash/blob/main/test/omitBy.spec.js
describe('omitBy', () => {
it('should work with a predicate argument', () => {
const object = { aa: 1, bb: 2, cc: 3, dd: 4 }
const actual = omitBy(object, (num) => num !== 2 && num !== 4)
expect(actual).toEqual({ bb: 2, dd: 4 })
})
})
})