avocado-old/packages/entity/trait/registrar.js
2020-06-30 09:14:05 -05:00

52 lines
1.1 KiB
JavaScript

const {all, idFrom: idFromRaw} = require('./traits.scwp');
const {registerHooks} = require('scwp');
let hasMapped = false;
const traitTo = new Map();
const typeTo = new Map();
export function allTraits() {
return Object.entries(all()).map(([, M]) => M.default);
}
function ensureTypeMap() {
if (!hasMapped) {
const entries = Object.entries(all());
for (let i = 0; i < entries.length; i++) {
const [, M] = entries[i];
const {default: Trait} = M;
typeTo.set(Trait.type(), Trait);
traitTo.set(Trait, M);
}
hasMapped = true;
}
}
export function idFrom(Trait) {
return idFromRaw(traitTo.get(Trait));
}
export function hasTrait(type) {
ensureTypeMap();
return typeTo.has(type);
}
export function lookupTrait(type) {
ensureTypeMap();
return typeTo.get(type);
}
registerHooks({
autoreg$accept: (type, M) => {
if ('trait' === type) {
const {default: Trait} = M;
typeTo.set(Trait.type(), Trait);
traitTo.set(Trait, M);
}
},
}, '@avocado/entity/trait/registrar');
if (module.hot) {
module.hot.accept(['./traits.scwp'], () => hasMapped = false);
}