Skip to content

Commit

Permalink
denormalizeDupes: dont clone the canvas source
Browse files Browse the repository at this point in the history
  • Loading branch information
city41 committed Jul 22, 2024
1 parent b6ba226 commit 071cd1c
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/api/tile/__tests__/denormalizeDupes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { BLACK24 } from '../../palette/colors';
import { getTestCanvas } from '../../../testUtil';
import { denormalizeDupes } from '../denormalizeDupes';

describe('denormalizeDupes', function () {
it('should maintain the original Canvas ref', function () {
const tile = {
cromIndex: 0,
canvasSource: getTestCanvas(BLACK24),
};

const deduped = denormalizeDupes([[[tile]]], 'cromIndex');

expect(tile).not.toBe(deduped[0][0][0]);
expect(tile.canvasSource).toBe(deduped[0][0][0].canvasSource);
});
});
33 changes: 32 additions & 1 deletion src/api/tile/denormalizeDupes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import cloneDeep from 'lodash/cloneDeep';
import { Canvas } from 'canvas';

/**
* If a tile is a dupe, it won't have a c/sromIndex but instead
Expand All @@ -11,16 +12,46 @@ import cloneDeep from 'lodash/cloneDeep';

type DupableTile = {
duplicateOf?: DupableTile;
canvasSource?: Canvas;
};

type MatrixRow<T extends DupableTile> = T[];
type Matrix<T extends DupableTile> = MatrixRow<T>[];

/**
* A Canvas cannot be cloned. So this method clones but copies the original Canvas
* ref, if any, back onto the clone
*/
function cloneDeepExceptCanvasSource<T extends DupableTile>(
tiles: Matrix<T>[]
): Matrix<T>[] {
const cloned = cloneDeep(tiles);

cloned.forEach((image, i) => {
image.forEach((row, r) => {
row.forEach((clonedTile, t) => {
if (clonedTile) {
const originalTile = tiles[i][r][t];

if (
originalTile &&
typeof originalTile.canvasSource !== 'undefined'
) {
clonedTile.canvasSource = originalTile.canvasSource;
}
}
});
});
});

return cloned;
}

export function denormalizeDupes<T extends DupableTile>(
tiles: Matrix<T>[],
indexProp: keyof T
): Matrix<T>[] {
const cloned = cloneDeep(tiles);
const cloned = cloneDeepExceptCanvasSource(tiles);

cloned.forEach((image) => {
image.forEach((row) => {
Expand Down

0 comments on commit 071cd1c

Please sign in to comment.