MediumTypeScript

Flyweight

TypeScriptDesign PatternsStructuralFlyweight

Share a single object instance across many usages of the same intrinsic state (here, a rendered character) instead of allocating a fresh one every time — a text editor shouldn't create a million distinct 'a' glyph objects for a million 'a' characters.

Implement `GlyphFactory.get(char)`: return the cached Glyph for that character, creating and caching it only the first time it's seen.

solve(text) renders every character through the factory and returns { rendered, uniqueGlyphs } — the cache size proves reuse.

solve('aab'){ rendered: '<a><a><b>', uniqueGlyphs: 2 } — two 'a's share one Glyph.

Sample tests

Test #1Repeated character shares a glyph
Input: ["aab"]
Output: {"rendered":"<a><a><b>","uniqueGlyphs":2}
Test #2Three distinct characters, repeated
Input: ["abcabc"]
Output: {"rendered":"<a><b><c><a><b><c>","uniqueGlyphs":3}
Test #3Empty string
Input: [""]
Output: {"rendered":"","uniqueGlyphs":0}