refactor: get

This commit is contained in:
cha0s 2022-09-17 07:37:02 -05:00
parent 91b649a4b0
commit ee4de8ac60
2 changed files with 26 additions and 4 deletions

View File

@ -265,15 +265,30 @@ export default class Ecs {
view.setUint32(0, entitiesWritten, true);
}
get(entity, Components = Object.keys(this.Components)) {
get(entity) {
if (!this.$$entities[entity]) {
return undefined;
}
const result = {};
for (let i = 0; i < Components.length; i++) {
const component = this.Components[Components[i]].get(entity);
for (let i = 0; i < this.$$entities[entity].length; i++) {
const component = this.Components[this.$$entities[entity][i]].get(entity);
if ('undefined' !== typeof component) {
result[Components[i]] = component;
result[this.$$entities[entity][i]] = component;
}
}
return result;
}
getUnsafe(entity) {
if (!this.$$entities[entity]) {
return undefined;
}
const result = {};
const components = this.$$entities[entity];
for (let i = 0; i < components.length; i++) {
const instance = this.Components[components[i]].getUnsafe(entity);
if ('undefined' !== typeof instance) {
result[components[i]] = instance;
}
}
return result;

View File

@ -20,6 +20,13 @@ it('can create entities with components', () => {
.to.deep.equal(JSON.stringify({Empty: {}, Position: {x: 32, y: 420, z: 0}}));
});
it('can get entities unsafely', () => {
const ecs = new Ecs({Empty, Position});
const entity = ecs.create({Empty: {}, Position: {y: 420}});
expect(JSON.stringify(ecs.getUnsafe(entity)))
.to.deep.equal(JSON.stringify({Empty: {}, Position: {x: 32, y: 420, z: 0}}));
});
it('can insert components into entities', () => {
const ecs = new Ecs({Empty, Position});
const entity = ecs.create({Empty: {}});