Skip to content

Open source personal finance application

refactor(utils): use Object.values in uniqueElementsBy and add tests

Ilya Komichevd92be3f85d9f
diff --git a/utils/simple.test.ts b/utils/simple.test.ts
new file mode 100644
index 00000000..80542bb1
--- /dev/null
+++ b/utils/simple.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest'
+
+import { uniqueElementsBy } from '~~/utils/simple'
+
+describe('uniqueElementsBy', () => {
+ it('extracts unique values of a property', () => {
+ const obj = {
+ a: { currency: 'USD', name: 'Cash' },
+ b: { currency: 'EUR', name: 'Card' },
+ c: { currency: 'USD', name: 'Savings' },
+ }
+
+ expect(uniqueElementsBy(obj, 'currency')).toEqual(['USD', 'EUR'])
+ })
+
+ it('returns empty array for empty object', () => {
+ expect(uniqueElementsBy({}, 'currency')).toEqual([])
+ })
+
+ it('returns single value when all entries are the same', () => {
+ const obj = {
+ a: { currency: 'RUB' },
+ b: { currency: 'RUB' },
+ }
+
+ expect(uniqueElementsBy(obj, 'currency')).toEqual(['RUB'])
+ })
+
+ it('does not traverse prototype chain', () => {
+ const proto = { inherited: { currency: 'HACK' } }
+ const obj = Object.create(proto)
+ obj.own = { currency: 'USD' }
+
+ expect(uniqueElementsBy(obj, 'currency')).toEqual(['USD'])
+ })
+})
diff --git a/utils/simple.ts b/utils/simple.ts
index 227454d8..538d775f 100644
--- a/utils/simple.ts
+++ b/utils/simple.ts
@@ -1,8 +1,7 @@
export function uniqueElementsBy<T extends object>(obj: { [key: string]: T }, propertyName: string): string[] {
const uniqueValues = new Set<string>()
- for (const key in obj) {
- const entry = obj[key]
+ for (const entry of Object.values(obj)) {
uniqueValues.add(entry[propertyName as keyof T] as string)
}