avocado-old/packages/behavior/item/collection.js

51 lines
1005 B
JavaScript
Raw Normal View History

2019-03-17 23:45:48 -05:00
import {fromJSON as behaviorItemFromJSON} from './registry';
export function Collection(type) {
2019-04-09 09:41:45 -05:00
const plural = `${type}s`;
2019-03-17 23:45:48 -05:00
return class Collection {
2019-05-05 04:26:35 -05:00
static type() {
return plural;
}
2019-03-17 23:45:48 -05:00
constructor() {
2019-04-09 09:41:45 -05:00
this[plural] = [];
2019-03-17 23:45:48 -05:00
}
2019-04-25 00:48:53 -05:00
clone(other) {
if (0 === other[plural].length) {
return;
}
const Item = other[plural][0].constructor;
for (let i = 0; i < other[plural].length; ++i) {
this[plural][i] = new Item();
this[plural][i].clone(other[plural][i]);
}
}
2019-09-08 07:40:07 -05:00
createClone() {
const Items = this.constructor;
const items = new Items();
items.clone(this);
return items;
}
2019-03-17 23:45:48 -05:00
count() {
2019-04-09 09:41:45 -05:00
return this[plural].length;
2019-03-17 23:45:48 -05:00
}
fromJSON(json) {
2019-04-09 09:41:45 -05:00
this[plural] = [];
2019-04-19 15:39:28 -05:00
for (const item of json[plural]) {
2019-04-09 09:41:45 -05:00
this[plural].push(behaviorItemFromJSON(item));
2019-03-17 23:45:48 -05:00
}
return this;
}
toJSON() {
2019-04-09 09:41:45 -05:00
return this[plural].map((item) => item.toJSON());
2019-03-17 23:45:48 -05:00
}
2019-04-19 15:39:28 -05:00
2019-03-17 23:45:48 -05:00
};
}