In this article, we analyse DefaultMap class in Tailwind CSS source code. This is a map that can generate default values for keys that don’t exist. Generated default values are added to the map to avoid re-computation.
/** * A Map that can generate default values for keys that don't exist. * Generated default values are added to the map to avoid recomputation. */export class DefaultMap<T = string, V = any> extends Map<T, V> { constructor(private factory: (key: T, self: DefaultMap<T, V>) => V) { super() } get(key: T): V { let value = super.get(key) if (value === undefined) { value = this.factory(key, this) this.set(key, value) } return value }}
In JavaScript, we have a Map API but there is no DefaultMap. This DefaultMap is a custom class that extends Map in Tailwind CSS source code.
DefaultMap is a class that has a constructor that expects a factory function. super() calls the parent class’s constructor, in this case, this is Map API and factory function’s second parameter is self: DefaultMap<T, V> which means it has access to Map instance.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.