collection.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. app.Collection = class Collection {
  2. constructor(objects) {
  3. if (objects == null) {
  4. objects = [];
  5. }
  6. this.reset(objects);
  7. }
  8. model() {
  9. return app.models[this.constructor.model];
  10. }
  11. reset(objects) {
  12. if (objects == null) {
  13. objects = [];
  14. }
  15. this.models = [];
  16. for (var object of objects) {
  17. this.add(object);
  18. }
  19. }
  20. add(object) {
  21. if (object instanceof app.Model) {
  22. this.models.push(object);
  23. } else if (object instanceof Array) {
  24. for (var obj of object) {
  25. this.add(obj);
  26. }
  27. } else if (object instanceof app.Collection) {
  28. this.models.push(...(object.all() || []));
  29. } else {
  30. this.models.push(new (this.model())(object));
  31. }
  32. }
  33. remove(model) {
  34. this.models.splice(this.models.indexOf(model), 1);
  35. }
  36. size() {
  37. return this.models.length;
  38. }
  39. isEmpty() {
  40. return this.models.length === 0;
  41. }
  42. each(fn) {
  43. for (var model of this.models) {
  44. fn(model);
  45. }
  46. }
  47. all() {
  48. return this.models;
  49. }
  50. contains(model) {
  51. return this.models.includes(model);
  52. }
  53. findBy(attr, value) {
  54. return this.models.find((model) => model[attr] === value);
  55. }
  56. findAllBy(attr, value) {
  57. return this.models.filter((model) => model[attr] === value);
  58. }
  59. countAllBy(attr, value) {
  60. let i = 0;
  61. for (var model of this.models) {
  62. if (model[attr] === value) {
  63. i += 1;
  64. }
  65. }
  66. return i;
  67. }
  68. };