Skip to content

Commit

Permalink
extract as a class
Browse files Browse the repository at this point in the history
  • Loading branch information
jordisala1991 committed Jun 18, 2024
1 parent c84a4c8 commit eb74156
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 14 deletions.
26 changes: 26 additions & 0 deletions plugin-src/Cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { LRUCache } from 'lru-cache';

const empty: unique symbol = Symbol('noValue');

// eslint-disable-next-line @typescript-eslint/ban-types
export class Cache<K extends {}, V extends {}> {
private cache: LRUCache<K, V | typeof empty>;

public constructor(options: LRUCache.Options<K, V | typeof empty, unknown>) {
this.cache = new LRUCache(options);
}

public get(key: K, calculate: () => V | undefined): V | undefined {
if (this.cache.has(key)) {
const cacheItem = this.cache.get(key);

return cacheItem === empty ? undefined : cacheItem;
}

const calculated = calculate();

this.cache.set(key, calculated ?? empty);

return calculated;
}
}
19 changes: 5 additions & 14 deletions plugin-src/translators/text/font/gfonts/translateGoogleFont.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { LRUCache } from 'lru-cache';
import slugify from 'slugify';

import { Cache } from '@plugin/Cache';
import { translateFontVariantId } from '@plugin/translators/text/font/gfonts';

import { FontId } from '@ui/lib/types/shapes/textShape';

import { items as gfonts } from './gfonts.json';
import { GoogleFont } from './googleFont';

const empty: unique symbol = Symbol('noValue');
const cache = new LRUCache<string, GoogleFont | typeof empty>({ max: 30 });
const fontsCache = new Cache<string, GoogleFont>({ max: 30 });

export const translateGoogleFont = (fontName: FontName, fontWeight: number): FontId | undefined => {
const googleFont = getGoogleFont(fontName);
Expand All @@ -27,15 +26,7 @@ export const isGoogleFont = (fontName: FontName): boolean => {
};

const getGoogleFont = (fontName: FontName): GoogleFont | undefined => {
if (cache.has(fontName.family)) {
const foo = cache.get(fontName.family);

return foo === empty ? undefined : foo;
}

const googleFont = gfonts.find(font => font.family === fontName.family);

cache.set(fontName.family, googleFont ?? empty);

return googleFont;
return fontsCache.get(fontName.family, () =>
gfonts.find(font => font.family === fontName.family)
);
};

0 comments on commit eb74156

Please sign in to comment.