dataFrameView.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { DataFrame, Vector } from '../types/index';
  2. /**
  3. * This abstraction will present the contents of a DataFrame as if
  4. * it were a well typed javascript object Vector.
  5. *
  6. * NOTE: The contents of the object returned from `view.get(index)`
  7. * are optimized for use in a loop. All calls return the same object
  8. * but the index has changed.
  9. *
  10. * For example, the three objects:
  11. * const first = view.get(0);
  12. * const second = view.get(1);
  13. * const third = view.get(2);
  14. * will point to the contents at index 2
  15. *
  16. * If you need three different objects, consider something like:
  17. * const first = { ... view.get(0) };
  18. * const second = { ... view.get(1) };
  19. * const third = { ... view.get(2) };
  20. */
  21. export class DataFrameView<T = any> implements Vector<T> {
  22. private index = 0;
  23. private obj: T;
  24. constructor(private data: DataFrame) {
  25. const obj = ({} as unknown) as T;
  26. for (let i = 0; i < data.fields.length; i++) {
  27. const field = data.fields[i];
  28. const getter = () => {
  29. return field.values.get(this.index);
  30. };
  31. if (!(obj as any).hasOwnProperty(field.name)) {
  32. Object.defineProperty(obj, field.name, {
  33. enumerable: true, // Shows up as enumerable property
  34. get: getter,
  35. });
  36. }
  37. Object.defineProperty(obj, i, {
  38. enumerable: false, // Don't enumerate array index
  39. get: getter,
  40. });
  41. }
  42. this.obj = obj;
  43. }
  44. get dataFrame() {
  45. return this.data;
  46. }
  47. get length() {
  48. return this.data.length;
  49. }
  50. get(idx: number) {
  51. this.index = idx;
  52. return this.obj;
  53. }
  54. toArray(): T[] {
  55. const arr: T[] = [];
  56. for (let i = 0; i < this.data.length; i++) {
  57. arr.push({ ...this.get(i) });
  58. }
  59. return arr;
  60. }
  61. toJSON(): T[] {
  62. return this.toArray();
  63. }
  64. forEachRow(iterator: (row: T) => void) {
  65. for (let i = 0; i < this.data.length; i++) {
  66. iterator(this.get(i));
  67. }
  68. }
  69. }