Skip to content

fix(cdk): preserve prototype chains in array helpers #1874

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
71 changes: 70 additions & 1 deletion libs/cdk/transformations/spec/array/toDictionary.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ describe('toDictionary', () => {
it('should create dictionary by symbol', () => {
const dictionaryResult = toDictionary(
Object.values(dictionaryBySymbol),
genus
genus,
);

expect(dictionaryResult).toEqual(dictionaryBySymbol);
Expand Down Expand Up @@ -142,4 +142,73 @@ describe('toDictionary', () => {
expect(toDictionary(arr2, '')).toEqual(undefined);
});
});

describe('prototype preservation', () => {
class TestClass {
constructor(
public id: number,
public value: string,
) {}

getDescription(): string {
return `${this.id}: ${this.value}`;
}
}

it('should preserve prototype chain when converting class instances to dictionary', () => {
const instances = [new TestClass(1, 'first'), new TestClass(2, 'second')];

const result = toDictionary(instances, 'id');

expect(result['1']).toBeInstanceOf(TestClass);
expect(result['2']).toBeInstanceOf(TestClass);

expect(result['1'].getDescription()).toBe('1: first');
expect(result['2'].getDescription()).toBe('2: second');
});

it('should preserve prototype chain with string keys', () => {
const instances = [new TestClass(1, 'cat'), new TestClass(2, 'dog')];

const result = toDictionary(instances, 'value');

expect(result['cat']).toBeInstanceOf(TestClass);
expect(result['dog']).toBeInstanceOf(TestClass);

expect(result['cat'].getDescription()).toBe('1: cat');
expect(result['dog'].getDescription()).toBe('2: dog');
});

it('should preserve prototype chain with symbol keys', () => {
const testSymbol = Symbol('test');

class SymbolClass {
[testSymbol]: string;

constructor(
public id: number,
symbolValue: string,
) {
this[testSymbol] = symbolValue;
}

getSymbolValue(): string {
return this[testSymbol];
}
}

const instances = [
new SymbolClass(1, 'first'),
new SymbolClass(2, 'second'),
];

const result = toDictionary(instances, testSymbol);

expect(result['first']).toBeInstanceOf(SymbolClass);
expect(result['second']).toBeInstanceOf(SymbolClass);

expect(result['first'].getSymbolValue()).toBe('first');
expect(result['second'].getSymbolValue()).toBe('second');
});
});
});
61 changes: 56 additions & 5 deletions libs/cdk/transformations/spec/array/update.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ describe('update', () => {
const result = update(
originalCreatures,
creaturesForUpdate[0],
(o, n) => o.id === n.id
(o, n) => o.id === n.id,
);

originalCreatures[0] = null as any;
Expand All @@ -89,25 +89,25 @@ describe('update', () => {
describe('functionality', () => {
it('should update value if matching by compareFn', () => {
expect(
update(creatures, creaturesForUpdate, (a, b) => a.id === b.id)
update(creatures, creaturesForUpdate, (a, b) => a.id === b.id),
).toEqual(creaturesAfterMultipleItemsUpdate);
});

it('should update value if matching by key', () => {
expect(update(creatures, creaturesForUpdate, 'id')).toEqual(
creaturesAfterMultipleItemsUpdate
creaturesAfterMultipleItemsUpdate,
);
});

it('should update value if matching by array of keys', () => {
expect(update(creatures, creaturesForUpdate, ['id'])).toEqual(
creaturesAfterMultipleItemsUpdate
creaturesAfterMultipleItemsUpdate,
);
});

it('should update partials', () => {
expect(update(creatures, { id: 1, type: 'lion' }, 'id')).toEqual(
creaturesAfterSingleItemUpdate
creaturesAfterSingleItemUpdate,
);
});
});
Expand Down Expand Up @@ -179,4 +179,55 @@ describe('update', () => {
});
});
});

describe('prototype preservation', () => {
class TestClass {
constructor(
public id: number,
public value: string,
) {}

getDescription(): string {
return `${this.id}: ${this.value}`;
}
}

it('should preserve prototype chain when updating class instances', () => {
const instances = [new TestClass(1, 'first'), new TestClass(2, 'second')];

const result = update(instances, { id: 1, value: 'updated' }, 'id');

expect(result[0]).toBeInstanceOf(TestClass);
expect(result[0].getDescription()).toBe('1: updated');

expect(result[1]).toBeInstanceOf(TestClass);
expect(result[1].getDescription()).toBe('2: second');
});

it('should preserve prototype chain when updating with comparison function', () => {
const instances = [new TestClass(1, 'first'), new TestClass(2, 'second')];

const result = update(
instances,
new TestClass(1, 'updated'),
(a, b) => a.id === b.id,
);

expect(result[0]).toBeInstanceOf(TestClass);
expect(result[1]).toBeInstanceOf(TestClass);
expect(result[0].getDescription()).toBe('1: updated');
expect(result[1].getDescription()).toBe('2: second');
});

it('should preserve prototype chain when no match is found', () => {
const instances = [new TestClass(1, 'first'), new TestClass(2, 'second')];

const result = update(instances, { id: 99, value: 'nonexistent' }, 'id');

expect(result[0]).toBeInstanceOf(TestClass);
expect(result[1]).toBeInstanceOf(TestClass);
expect(result[0].getDescription()).toBe('1: first');
expect(result[1].getDescription()).toBe('2: second');
});
});
});
64 changes: 58 additions & 6 deletions libs/cdk/transformations/spec/array/upsert.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ describe('upsert', () => {
upsert(
originalCreatures,
creaturesForUpdate[0],
(o, n) => o.id === n.id
(o, n) => o.id === n.id,
);

expect(originalCreatures).toEqual(creatures);
Expand All @@ -76,7 +76,7 @@ describe('upsert', () => {
const result = upsert(
originalCreatures,
creaturesForUpdate[0],
(o, n) => o.id === n.id
(o, n) => o.id === n.id,
);
const result2 = upsert(null as any, originalCreatures);

Expand All @@ -98,25 +98,25 @@ describe('upsert', () => {
describe('functionality', () => {
it('should update value if matching by compareFn', () => {
expect(
upsert(creatures, creaturesForUpdate, (a, b) => a.id === b.id)
upsert(creatures, creaturesForUpdate, (a, b) => a.id === b.id),
).toEqual(creaturesAfterMultipleItemsUpdate);
});

it('should update value if matching by key', () => {
expect(upsert(creatures, creaturesForUpdate, 'id')).toEqual(
creaturesAfterMultipleItemsUpdate
creaturesAfterMultipleItemsUpdate,
);
});

it('should update value if matching by array of keys', () => {
expect(upsert(creatures, creaturesForUpdate, ['id'])).toEqual(
creaturesAfterMultipleItemsUpdate
creaturesAfterMultipleItemsUpdate,
);
});

it('should update partials', () => {
expect(upsert(creatures, { id: 1, type: 'lion' }, 'id')).toEqual(
creaturesAfterSingleItemUpdate
creaturesAfterSingleItemUpdate,
);
});
});
Expand Down Expand Up @@ -318,4 +318,56 @@ describe('upsert', () => {
});
});
});

describe('prototype preservation', () => {
class TestClass {
constructor(
public id: number,
public value: string,
) {}

getDescription(): string {
return `${this.id}: ${this.value}`;
}
}

it('should preserve prototype chain when updating class instances', () => {
const instances = [new TestClass(1, 'first'), new TestClass(2, 'second')];

const result = upsert(instances, { id: 1, value: 'updated' }, 'id');

expect(result[0]).toBeInstanceOf(TestClass);
expect(result[0].getDescription()).toBe('1: updated');

expect(result[1]).toBeInstanceOf(TestClass);
expect(result[1].getDescription()).toBe('2: second');
});

it('should preserve prototype chain when inserting class instances', () => {
const instances = [new TestClass(1, 'first'), new TestClass(2, 'second')];

const result = upsert(instances, new TestClass(3, 'third'), 'id');

expect(result[0]).toBeInstanceOf(TestClass);
expect(result[1]).toBeInstanceOf(TestClass);

expect(result[2]).toBeInstanceOf(TestClass);
expect(result[2].getDescription()).toBe('3: third');
});

it('should preserve prototype chain when upserting with comparison function', () => {
const instances = [new TestClass(1, 'first'), new TestClass(2, 'second')];

const result = upsert(
instances,
new TestClass(1, 'updated'),
(a, b) => a.id === b.id,
);

expect(result[0]).toBeInstanceOf(TestClass);
expect(result[1]).toBeInstanceOf(TestClass);
expect(result[0].getDescription()).toBe('1: updated');
expect(result[1].getDescription()).toBe('2: second');
});
});
});
13 changes: 10 additions & 3 deletions libs/cdk/transformations/src/lib/array/toDictionary.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { isDefined, isKeyOf, OnlyKeysOfSpecificType } from '../_internals/guards';
import {
isDefined,
isKeyOf,
OnlyKeysOfSpecificType,
} from '../_internals/guards';

/**
* @description
Expand Down Expand Up @@ -53,7 +57,7 @@ export function toDictionary<T extends object>(
key:
| OnlyKeysOfSpecificType<T, number>
| OnlyKeysOfSpecificType<T, string>
| OnlyKeysOfSpecificType<T, symbol>
| OnlyKeysOfSpecificType<T, symbol>,
): { [key: string]: T } {
if (!isDefined(source)) {
return source;
Expand All @@ -73,7 +77,10 @@ export function toDictionary<T extends object>(
let i = 0;

for (i; i < length; i++) {
dictionary[`${source[i][key]}`] = Object.assign({}, source[i]);
dictionary[`${source[i][key]}`] = Object.assign(
Object.create(Object.getPrototypeOf(source[i])),
source[i],
);
}

return dictionary;
Expand Down
14 changes: 11 additions & 3 deletions libs/cdk/transformations/src/lib/array/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ import { ComparableData } from '../interfaces/comparable-data-type';
export function update<T extends object>(
source: T[],
updates: Partial<T>[] | Partial<T>,
compare?: ComparableData<T>
compare?: ComparableData<T>,
): T[] {
const updatesDefined = updates != null;
const updatesAsArray = updatesDefined
Expand All @@ -101,10 +101,18 @@ export function update<T extends object>(
const x: T[] = [];
for (const existingItem of source) {
const match = customFind(updatesAsArray, (item) =>
valuesComparer(item as T, existingItem, compare)
valuesComparer(item as T, existingItem, compare),
);

x.push(match ? { ...existingItem, ...match } : existingItem);
x.push(
match
? Object.assign(
Object.create(Object.getPrototypeOf(existingItem)),
existingItem,
match,
)
: existingItem,
);
}

return x;
Expand Down
15 changes: 10 additions & 5 deletions libs/cdk/transformations/src/lib/array/upsert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ import { ComparableData } from '../interfaces/comparable-data-type';
export function upsert<T>(
source: T[],
update: Partial<T>[] | Partial<T>,
compare?: ComparableData<T>
compare?: ComparableData<T>,
): T[] {
// check inputs for validity
const updatesAsArray =
Expand All @@ -120,16 +120,17 @@ export function upsert<T>(
// process updates/inserts
for (const item of updatesAsArray) {
const match = source.findIndex((sourceItem) =>
valuesComparer(item as T, sourceItem, compare)
valuesComparer(item as T, sourceItem, compare),
);
// if item already exists, save it as update
if (match !== -1) {
updates[match] = item;
} else {
// otherwise consider this as insert
if (isObjectGuard(item)) {
// create a shallow copy if item is an object
inserts.push({ ...(item as T) });
inserts.push(
Object.assign(Object.create(Object.getPrototypeOf(item)), item) as T,
);
} else {
// otherwise just push it
inserts.push(item);
Expand All @@ -142,7 +143,11 @@ export function upsert<T>(
// process the updated
if (updatedItem !== null && updatedItem !== undefined) {
if (isObjectGuard(item)) {
return { ...item, ...updatedItem } as T;
return Object.assign(
Object.create(Object.getPrototypeOf(item)),
item,
updatedItem,
) as T;
} else {
return updatedItem as T;
}
Expand Down
Loading