sample.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Sample = void 0;
  4. // @ts-ignore medianIndex exist in d3-array@3.2.0, but @types/d3-array Expired.
  5. const d3_array_1 = require("d3-array");
  6. const order_1 = require("./utils/order");
  7. const helper_1 = require("./utils/helper");
  8. const lttb_1 = require("./utils/lttb");
  9. function normalizeSample(strategy) {
  10. if (typeof strategy === 'function')
  11. return strategy;
  12. if (strategy === 'lttb')
  13. return lttb_1.lttb;
  14. const strategies = {
  15. first: (f) => [f[0]],
  16. last: (f) => [f[f.length - 1]],
  17. min: (f, X, Y) => [
  18. f[(0, d3_array_1.minIndex)(f, (i) => Y[i])],
  19. ],
  20. max: (f, X, Y) => [
  21. f[(0, d3_array_1.maxIndex)(f, (i) => Y[i])],
  22. ],
  23. median: (f, X, Y) => [
  24. f[(0, d3_array_1.medianIndex)(f, (i) => Y[i])],
  25. ],
  26. };
  27. const sampleFunction = strategies[strategy] || strategies.median;
  28. return (I, X, Y, thresholds) => {
  29. // Sepreate group to frames, then sample each frame.
  30. // Keep more data as possible.
  31. const frameSize = Math.max(1, Math.floor(I.length / thresholds));
  32. const frames = getFrames(I, frameSize);
  33. return frames.flatMap((frame) => sampleFunction(frame, X, Y));
  34. };
  35. }
  36. /**
  37. * Split the array into frame with each frameSize.
  38. */
  39. function getFrames(I, frameSize) {
  40. const size = I.length;
  41. const frames = [];
  42. let i = 0;
  43. while (i < size) {
  44. frames.push(I.slice(i, (i += frameSize)));
  45. }
  46. return frames;
  47. }
  48. /**
  49. * The sample transform groups marks with specified groupBy fields, and
  50. * sample data for each group when data.length >= threshold(default = 2000).
  51. */
  52. const Sample = (options = {}) => {
  53. const { strategy = 'median', thresholds = 2000, groupBy = ['series', 'color'], } = options;
  54. const sampleFunction = normalizeSample(strategy);
  55. return (I, mark) => {
  56. const { encode } = mark;
  57. const groups = (0, order_1.createGroups)(groupBy, I, mark);
  58. const [X] = (0, helper_1.columnOf)(encode, 'x');
  59. const [Y] = (0, helper_1.columnOf)(encode, 'y');
  60. return [
  61. groups.flatMap((g) => sampleFunction(g, X, Y, thresholds)),
  62. mark,
  63. ];
  64. };
  65. };
  66. exports.Sample = Sample;
  67. exports.Sample.props = {};
  68. //# sourceMappingURL=sample.js.map