avocado-old/packages/behavior/item/collection.js
2019-04-25 00:48:53 -05:00

40 lines
812 B
JavaScript

import {fromJSON as behaviorItemFromJSON} from './registry';
export function Collection(type) {
const plural = `${type}s`;
return class Collection {
constructor() {
this[plural] = [];
}
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]);
}
}
count() {
return this[plural].length;
}
fromJSON(json) {
this[plural] = [];
for (const item of json[plural]) {
this[plural].push(behaviorItemFromJSON(item));
}
return this;
}
toJSON() {
return this[plural].map((item) => item.toJSON());
}
};
}