Mercurial > personal > weather-server
view weather_server/typescript/amd/mad-amd.ts @ 14:dd77a7ee02c1
Create tiny AMD loader and set up tsc for it.
author | Paul Fisher <paul@pfish.zone> |
---|---|
date | Wed, 09 Oct 2019 23:14:16 -0400 |
parents | |
children | df3e0534c994 |
line wrap: on
line source
// TODO: add more comments. /** * The dumbest possible implementation of AMD to handle only the code that * `tsc -m amd` produces. */ class Registry { private readonly modules = new Map<string, Module>(); private readonly reified = new Map<string, {}>(); define(name: string, deps: string[], factory: FactoryFunction) { this.modules.set(name, {deps, factory, exports: {}}); } require(dep: string, srcMod?: Module): {} { if (dep === 'require') { return (child: string) => this.require(child, srcMod); } if (dep === 'exports') { if (!srcMod) throw new Error('Invalid package name.'); return srcMod.exports; } const exp = this.reified.get(dep); if (exp) return exp; const mod = this.modules.get(dep); if (!mod) throw new Error('Undefined module.'); this.reified.set(dep, mod.exports); const deps = mod.deps.map(child => this.require(child, mod)); mod.factory(...deps); return mod.exports; } install() { self.define = (name: string, deps: string[], factory: FactoryFunction) => this.define(name, deps, factory); self.require = (dep: string) => this.require(dep); } } (() => new Registry().install())();