computedArray.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.computedArray = void 0;
  4. const computed_1 = require("../computed");
  5. function computedArray(arr, computedItem) {
  6. const length = (0, computed_1.computed)(() => arr().length);
  7. const keys = (0, computed_1.computed)(() => {
  8. const keys = [];
  9. for (let i = 0; i < length(); i++) {
  10. keys.push(String(i));
  11. }
  12. return keys;
  13. });
  14. const items = (0, computed_1.computed)((array) => {
  15. array ??= [];
  16. while (array.length < length()) {
  17. const index = array.length;
  18. const item = (0, computed_1.computed)(() => arr()[index]);
  19. array.push(computedItem(item, index));
  20. }
  21. if (array.length > length()) {
  22. array.length = length();
  23. }
  24. return array;
  25. });
  26. return new Proxy({}, {
  27. get(_, p, receiver) {
  28. if (p === 'length') {
  29. return length();
  30. }
  31. if (typeof p === 'string' && !isNaN(Number(p))) {
  32. return items()[Number(p)]?.();
  33. }
  34. return Reflect.get(items(), p, receiver);
  35. },
  36. has(_, p) {
  37. return Reflect.has(items(), p);
  38. },
  39. ownKeys() {
  40. return keys();
  41. },
  42. });
  43. }
  44. exports.computedArray = computedArray;