feat: hot traits

This commit is contained in:
cha0s 2020-06-17 23:56:31 -05:00
parent 2a2b9fd8eb
commit c65612a387

View File

@ -1,16 +1,20 @@
const {all, idFrom: idFromRaw} = require('./traits.scwp');
const {registerHooks} = require('scwp');
let hasMapped = false;
const traitTo = new Map();
const typeTo = new Map();
function mapTypesToTraits() {
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);
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;
}
}
@ -19,19 +23,21 @@ export function idFrom(Trait) {
}
export function hasTrait(type) {
if (!hasMapped) {
mapTypesToTraits();
hasMapped = true;
}
ensureTypeMap();
return typeTo.has(type);
}
export function lookupTrait(type) {
if (!hasMapped) {
mapTypesToTraits();
hasMapped = true;
}
ensureTypeMap();
return typeTo.get(type);
}
registerHooks({
autoreg$accept: (type, M) => {
const {default: Trait} = M;
typeTo.set(Trait.type(), Trait);
traitTo.set(Trait, M);
},
}, '@avocado/entity/trait/registrar');
module.hot?.accept(['./traits.scwp'], () => hasMapped = false);