Skip to content
Draft
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
4 changes: 2 additions & 2 deletions src/asset-loading/asset-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ export interface AssetCache<T> {
/**
* Retrieves an asset from the cache.
* @param key - The key of the asset to retrieve.
* @returns The cached asset.
* @returns The cached asset, or null if not found in the cache.
*/
get: (key: string) => T;
get: (key: string) => T | null;

/**
* Loads an asset from the specified key and caches it.
Expand Down
6 changes: 2 additions & 4 deletions src/asset-loading/asset-caches/image-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,10 @@ describe('ImageCache', () => {
expect(retrievedImage).toBe(mockImage);
});

it('should throw an error if the image is not found in the cache', () => {
it('should return null if the image is not found in the cache', () => {
const imageCache = new ImageCache();

expect(() => imageCache.get('path/to/nonexistent.png')).toThrow(
'Image with path "path/to/nonexistent.png" not found in store.',
);
expect(imageCache.get('path/to/nonexistent.png')).toBeNull();
});

it('should load and cache an image', async () => {
Expand Down
22 changes: 11 additions & 11 deletions src/asset-loading/asset-caches/image-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,10 @@ export class ImageCache implements AssetCache<HTMLImageElement> {
/**
* Retrieves an image from the cache.
* @param path - The path of the image to retrieve.
* @returns The cached image element.
* @throws Will throw an error if the image is not found in the cache.
* @returns The cached image element, or null if not found in the cache.
*/
public get(path: string): HTMLImageElement {
const image = this.assets.get(path);

if (!image) {
throw new Error(`Image with path "${path}" not found in store.`);
}

return image;
public get(path: string): HTMLImageElement | null {
return this.assets.get(path) ?? null;
}

/**
Expand Down Expand Up @@ -53,12 +46,19 @@ export class ImageCache implements AssetCache<HTMLImageElement> {
* Retrieves an image from the cache if it exists, otherwise loads and caches it.
* @param path - The path of the image to retrieve or load.
* @returns A promise that resolves to the image element.
* @throws Will throw an error if the image fails to load.
*/
public async getOrLoad(path: string): Promise<HTMLImageElement> {
if (!this.assets.has(path)) {
await this.load(path);
}

return this.get(path);
const image = this.get(path);

if (image === null) {
throw new Error(`Image with path "${path}" not found in store.`);
}

return image;
}
}
Loading