collection.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // TODO: This file was created by bulk-decaffeinate.
  2. // Sanity-check the conversion and remove this comment.
  3. /*
  4. * decaffeinate suggestions:
  5. * DS101: Remove unnecessary use of Array.from
  6. * DS102: Remove unnecessary code created because of implicit returns
  7. * DS207: Consider shorter variations of null checks
  8. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
  9. */
  10. app.Collection = class Collection {
  11. constructor(objects) {
  12. if (objects == null) {
  13. objects = [];
  14. }
  15. this.reset(objects);
  16. }
  17. model() {
  18. return app.models[this.constructor.model];
  19. }
  20. reset(objects) {
  21. if (objects == null) {
  22. objects = [];
  23. }
  24. this.models = [];
  25. for (var object of Array.from(objects)) {
  26. this.add(object);
  27. }
  28. }
  29. add(object) {
  30. if (object instanceof app.Model) {
  31. this.models.push(object);
  32. } else if (object instanceof Array) {
  33. for (var obj of Array.from(object)) {
  34. this.add(obj);
  35. }
  36. } else if (object instanceof app.Collection) {
  37. this.models.push(...Array.from(object.all() || []));
  38. } else {
  39. this.models.push(new (this.model())(object));
  40. }
  41. }
  42. remove(model) {
  43. this.models.splice(this.models.indexOf(model), 1);
  44. }
  45. size() {
  46. return this.models.length;
  47. }
  48. isEmpty() {
  49. return this.models.length === 0;
  50. }
  51. each(fn) {
  52. for (var model of Array.from(this.models)) {
  53. fn(model);
  54. }
  55. }
  56. all() {
  57. return this.models;
  58. }
  59. contains(model) {
  60. return this.models.indexOf(model) >= 0;
  61. }
  62. findBy(attr, value) {
  63. for (var model of Array.from(this.models)) {
  64. if (model[attr] === value) {
  65. return model;
  66. }
  67. }
  68. }
  69. findAllBy(attr, value) {
  70. return Array.from(this.models).filter((model) => model[attr] === value);
  71. }
  72. countAllBy(attr, value) {
  73. let i = 0;
  74. for (var model of Array.from(this.models)) {
  75. if (model[attr] === value) {
  76. i += 1;
  77. }
  78. }
  79. return i;
  80. }
  81. };