@vitessce/utils 3.5.5 → 3.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -442,6 +442,279 @@ function getInitialCoordinationScopeName(datasetUid, dataType, i = null) {
442
442
  const prefix = getInitialCoordinationScopePrefix(datasetUid, dataType);
443
443
  return `${prefix}${i === null ? 0 : i}`;
444
444
  }
445
+ const identityFunc = (d) => d;
446
+ function unnestMap(map, keys, aggFunc) {
447
+ if (keys.length < 2) {
448
+ throw new Error("Insufficient number of keys passed to flattenInternMap");
449
+ }
450
+ const aggFuncToUse = !aggFunc ? identityFunc : aggFunc;
451
+ return Array.from(map.entries()).flatMap(([k, v]) => {
452
+ if (v instanceof Map) {
453
+ const keysWithoutFirst = [...keys];
454
+ keysWithoutFirst.splice(0, 1);
455
+ return unnestMap(v, keysWithoutFirst, aggFuncToUse).map((childObj) => ({
456
+ [keys[0]]: k,
457
+ ...childObj
458
+ }));
459
+ }
460
+ return {
461
+ [keys[0]]: k,
462
+ [keys[1]]: aggFuncToUse(v)
463
+ };
464
+ });
465
+ }
466
+ var loglevel = { exports: {} };
467
+ (function(module) {
468
+ (function(root, definition) {
469
+ if (module.exports) {
470
+ module.exports = definition();
471
+ } else {
472
+ root.log = definition();
473
+ }
474
+ })(commonjsGlobal, function() {
475
+ var noop = function() {
476
+ };
477
+ var undefinedType = "undefined";
478
+ var isIE = typeof window !== undefinedType && typeof window.navigator !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent);
479
+ var logMethods = [
480
+ "trace",
481
+ "debug",
482
+ "info",
483
+ "warn",
484
+ "error"
485
+ ];
486
+ var _loggersByName = {};
487
+ var defaultLogger = null;
488
+ function bindMethod(obj, methodName) {
489
+ var method = obj[methodName];
490
+ if (typeof method.bind === "function") {
491
+ return method.bind(obj);
492
+ } else {
493
+ try {
494
+ return Function.prototype.bind.call(method, obj);
495
+ } catch (e) {
496
+ return function() {
497
+ return Function.prototype.apply.apply(method, [obj, arguments]);
498
+ };
499
+ }
500
+ }
501
+ }
502
+ function traceForIE() {
503
+ if (console.log) {
504
+ if (console.log.apply) {
505
+ console.log.apply(console, arguments);
506
+ } else {
507
+ Function.prototype.apply.apply(console.log, [console, arguments]);
508
+ }
509
+ }
510
+ if (console.trace)
511
+ console.trace();
512
+ }
513
+ function realMethod(methodName) {
514
+ if (methodName === "debug") {
515
+ methodName = "log";
516
+ }
517
+ if (typeof console === undefinedType) {
518
+ return false;
519
+ } else if (methodName === "trace" && isIE) {
520
+ return traceForIE;
521
+ } else if (console[methodName] !== void 0) {
522
+ return bindMethod(console, methodName);
523
+ } else if (console.log !== void 0) {
524
+ return bindMethod(console, "log");
525
+ } else {
526
+ return noop;
527
+ }
528
+ }
529
+ function replaceLoggingMethods() {
530
+ var level = this.getLevel();
531
+ for (var i = 0; i < logMethods.length; i++) {
532
+ var methodName = logMethods[i];
533
+ this[methodName] = i < level ? noop : this.methodFactory(methodName, level, this.name);
534
+ }
535
+ this.log = this.debug;
536
+ if (typeof console === undefinedType && level < this.levels.SILENT) {
537
+ return "No console available for logging";
538
+ }
539
+ }
540
+ function enableLoggingWhenConsoleArrives(methodName) {
541
+ return function() {
542
+ if (typeof console !== undefinedType) {
543
+ replaceLoggingMethods.call(this);
544
+ this[methodName].apply(this, arguments);
545
+ }
546
+ };
547
+ }
548
+ function defaultMethodFactory(methodName, _level, _loggerName) {
549
+ return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
550
+ }
551
+ function Logger(name, factory) {
552
+ var self2 = this;
553
+ var inheritedLevel;
554
+ var defaultLevel;
555
+ var userLevel;
556
+ var storageKey = "loglevel";
557
+ if (typeof name === "string") {
558
+ storageKey += ":" + name;
559
+ } else if (typeof name === "symbol") {
560
+ storageKey = void 0;
561
+ }
562
+ function persistLevelIfPossible(levelNum) {
563
+ var levelName = (logMethods[levelNum] || "silent").toUpperCase();
564
+ if (typeof window === undefinedType || !storageKey)
565
+ return;
566
+ try {
567
+ window.localStorage[storageKey] = levelName;
568
+ return;
569
+ } catch (ignore) {
570
+ }
571
+ try {
572
+ window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
573
+ } catch (ignore) {
574
+ }
575
+ }
576
+ function getPersistedLevel() {
577
+ var storedLevel;
578
+ if (typeof window === undefinedType || !storageKey)
579
+ return;
580
+ try {
581
+ storedLevel = window.localStorage[storageKey];
582
+ } catch (ignore) {
583
+ }
584
+ if (typeof storedLevel === undefinedType) {
585
+ try {
586
+ var cookie = window.document.cookie;
587
+ var cookieName = encodeURIComponent(storageKey);
588
+ var location = cookie.indexOf(cookieName + "=");
589
+ if (location !== -1) {
590
+ storedLevel = /^([^;]+)/.exec(
591
+ cookie.slice(location + cookieName.length + 1)
592
+ )[1];
593
+ }
594
+ } catch (ignore) {
595
+ }
596
+ }
597
+ if (self2.levels[storedLevel] === void 0) {
598
+ storedLevel = void 0;
599
+ }
600
+ return storedLevel;
601
+ }
602
+ function clearPersistedLevel() {
603
+ if (typeof window === undefinedType || !storageKey)
604
+ return;
605
+ try {
606
+ window.localStorage.removeItem(storageKey);
607
+ } catch (ignore) {
608
+ }
609
+ try {
610
+ window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
611
+ } catch (ignore) {
612
+ }
613
+ }
614
+ function normalizeLevel(input) {
615
+ var level = input;
616
+ if (typeof level === "string" && self2.levels[level.toUpperCase()] !== void 0) {
617
+ level = self2.levels[level.toUpperCase()];
618
+ }
619
+ if (typeof level === "number" && level >= 0 && level <= self2.levels.SILENT) {
620
+ return level;
621
+ } else {
622
+ throw new TypeError("log.setLevel() called with invalid level: " + input);
623
+ }
624
+ }
625
+ self2.name = name;
626
+ self2.levels = {
627
+ "TRACE": 0,
628
+ "DEBUG": 1,
629
+ "INFO": 2,
630
+ "WARN": 3,
631
+ "ERROR": 4,
632
+ "SILENT": 5
633
+ };
634
+ self2.methodFactory = factory || defaultMethodFactory;
635
+ self2.getLevel = function() {
636
+ if (userLevel != null) {
637
+ return userLevel;
638
+ } else if (defaultLevel != null) {
639
+ return defaultLevel;
640
+ } else {
641
+ return inheritedLevel;
642
+ }
643
+ };
644
+ self2.setLevel = function(level, persist) {
645
+ userLevel = normalizeLevel(level);
646
+ if (persist !== false) {
647
+ persistLevelIfPossible(userLevel);
648
+ }
649
+ return replaceLoggingMethods.call(self2);
650
+ };
651
+ self2.setDefaultLevel = function(level) {
652
+ defaultLevel = normalizeLevel(level);
653
+ if (!getPersistedLevel()) {
654
+ self2.setLevel(level, false);
655
+ }
656
+ };
657
+ self2.resetLevel = function() {
658
+ userLevel = null;
659
+ clearPersistedLevel();
660
+ replaceLoggingMethods.call(self2);
661
+ };
662
+ self2.enableAll = function(persist) {
663
+ self2.setLevel(self2.levels.TRACE, persist);
664
+ };
665
+ self2.disableAll = function(persist) {
666
+ self2.setLevel(self2.levels.SILENT, persist);
667
+ };
668
+ self2.rebuild = function() {
669
+ if (defaultLogger !== self2) {
670
+ inheritedLevel = normalizeLevel(defaultLogger.getLevel());
671
+ }
672
+ replaceLoggingMethods.call(self2);
673
+ if (defaultLogger === self2) {
674
+ for (var childName in _loggersByName) {
675
+ _loggersByName[childName].rebuild();
676
+ }
677
+ }
678
+ };
679
+ inheritedLevel = normalizeLevel(
680
+ defaultLogger ? defaultLogger.getLevel() : "WARN"
681
+ );
682
+ var initialLevel = getPersistedLevel();
683
+ if (initialLevel != null) {
684
+ userLevel = normalizeLevel(initialLevel);
685
+ }
686
+ replaceLoggingMethods.call(self2);
687
+ }
688
+ defaultLogger = new Logger();
689
+ defaultLogger.getLogger = function getLogger(name) {
690
+ if (typeof name !== "symbol" && typeof name !== "string" || name === "") {
691
+ throw new TypeError("You must supply a name when creating a logger.");
692
+ }
693
+ var logger = _loggersByName[name];
694
+ if (!logger) {
695
+ logger = _loggersByName[name] = new Logger(
696
+ name,
697
+ defaultLogger.methodFactory
698
+ );
699
+ }
700
+ return logger;
701
+ };
702
+ var _log = typeof window !== undefinedType ? window.log : void 0;
703
+ defaultLogger.noConflict = function() {
704
+ if (typeof window !== undefinedType && window.log === defaultLogger) {
705
+ window.log = _log;
706
+ }
707
+ return defaultLogger;
708
+ };
709
+ defaultLogger.getLoggers = function getLoggers() {
710
+ return _loggersByName;
711
+ };
712
+ defaultLogger["default"] = defaultLogger;
713
+ return defaultLogger;
714
+ });
715
+ })(loglevel);
716
+ var loglevelExports = loglevel.exports;
717
+ const log = /* @__PURE__ */ getDefaultExportFromCjs(loglevelExports);
445
718
  const DEFAULT_DARK_COLOR = [50, 50, 50];
446
719
  const DEFAULT_LIGHT_COLOR = [200, 200, 200];
447
720
  const DEFAULT_LIGHT2_COLOR = [235, 235, 235];
@@ -511,22 +784,22 @@ const COLORMAP_OPTIONS = [
511
784
  ];
512
785
  const DEFAULT_GL_OPTIONS = { webgl2: true };
513
786
  function createDefaultUpdateStatus(componentName) {
514
- return (message) => console.warn(`${componentName} updateStatus: ${message}`);
787
+ return (message) => log.warn(`${componentName} updateStatus: ${message}`);
515
788
  }
516
789
  function createDefaultUpdateCellsSelection(componentName) {
517
- return (cellsSelection) => console.warn(`${componentName} updateCellsSelection: ${cellsSelection}`);
790
+ return (cellsSelection) => log.warn(`${componentName} updateCellsSelection: ${cellsSelection}`);
518
791
  }
519
792
  function createDefaultUpdateCellsHover(componentName) {
520
- return (hoverInfo) => console.warn(`${componentName} updateCellsHover: ${hoverInfo.cellId}`);
793
+ return (hoverInfo) => log.warn(`${componentName} updateCellsHover: ${hoverInfo.cellId}`);
521
794
  }
522
795
  function createDefaultUpdateGenesHover(componentName) {
523
- return (hoverInfo) => console.warn(`${componentName} updateGenesHover: ${hoverInfo.geneId}`);
796
+ return (hoverInfo) => log.warn(`${componentName} updateGenesHover: ${hoverInfo.geneId}`);
524
797
  }
525
798
  function createDefaultUpdateTracksHover(componentName) {
526
- return (hoverInfo) => console.warn(`${componentName} updateTracksHover: ${hoverInfo}`);
799
+ return (hoverInfo) => log.warn(`${componentName} updateTracksHover: ${hoverInfo}`);
527
800
  }
528
801
  function createDefaultUpdateViewInfo(componentName) {
529
- return (viewInfo) => console.warn(`${componentName} updateViewInfo: ${viewInfo}`);
802
+ return (viewInfo) => log.warn(`${componentName} updateViewInfo: ${viewInfo}`);
530
803
  }
531
804
  function createDefaultClearPleaseWait() {
532
805
  return () => {
@@ -653,5 +926,6 @@ export {
653
926
  getNextScope,
654
927
  getNextScopeNumeric,
655
928
  getValueTransformFunction,
656
- pluralize
929
+ pluralize,
930
+ unnestMap
657
931
  };
@@ -1 +1 @@
1
- {"version":3,"file":"components.d.ts","sourceRoot":"","sources":["../src/components.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,kBAAkB,UAAe,CAAC;AAC/C,eAAO,MAAM,mBAAmB,UAAkB,CAAC;AACnD,eAAO,MAAM,oBAAoB,UAAkB,CAAC;AAEpD,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,QAAQ,YAKjE;AAGD,eAAO,MAAM,OAAO,YAUnB,CAAC;AAEF,eAAO,MAAM,cAAc,YAS1B,CAAC;AAEF,eAAO,MAAM,iBAAiB,YAS7B,CAAC;AAEF,eAAO,MAAM,uBAAuB,YAiBnC,CAAC;AAEF,eAAO,MAAM,gBAAgB,UAW5B,CAAC;AAEF,eAAO,MAAM,kBAAkB;;CAAmB,CAAC;AAEnD,wBAAgB,yBAAyB,CAAC,aAAa,EAAE,MAAM,aAC5C,MAAM,UACxB;AAED,wBAAgB,iCAAiC,CAAC,aAAa,EAAE,MAAM,oBAC7C,GAAG,UAC5B;AAED,wBAAgB,6BAA6B,CAAC,aAAa,EAAE,MAAM,eAC9C;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,UACtC;AAED,wBAAgB,6BAA6B,CAAC,aAAa,EAAE,MAAM,eAC9C;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,UACtC;AAED,wBAAgB,8BAA8B,CAAC,aAAa,EAAE,MAAM,eAC/C,GAAG,UACvB;AAED,wBAAgB,2BAA2B,CAAC,aAAa,EAAE,MAAM,cAC7C,GAAG,UACtB;AAED,wBAAgB,4BAA4B,eAG3C;AAGD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,cAK7C;AAED,wBAAgB,UAAU,CAAC,SAAS,EAAE,GAAG;;;EAKxC;AAGD,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,SAAI,UAWtD"}
1
+ {"version":3,"file":"components.d.ts","sourceRoot":"","sources":["../src/components.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,kBAAkB,UAAe,CAAC;AAC/C,eAAO,MAAM,mBAAmB,UAAkB,CAAC;AACnD,eAAO,MAAM,oBAAoB,UAAkB,CAAC;AAEpD,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,QAAQ,YAKjE;AAGD,eAAO,MAAM,OAAO,YAUnB,CAAC;AAEF,eAAO,MAAM,cAAc,YAS1B,CAAC;AAEF,eAAO,MAAM,iBAAiB,YAS7B,CAAC;AAEF,eAAO,MAAM,uBAAuB,YAiBnC,CAAC;AAEF,eAAO,MAAM,gBAAgB,UAW5B,CAAC;AAEF,eAAO,MAAM,kBAAkB;;CAAmB,CAAC;AAEnD,wBAAgB,yBAAyB,CAAC,aAAa,EAAE,MAAM,aAC5C,MAAM,UACxB;AAED,wBAAgB,iCAAiC,CAAC,aAAa,EAAE,MAAM,oBAC7C,GAAG,UAC5B;AAED,wBAAgB,6BAA6B,CAAC,aAAa,EAAE,MAAM,eAC9C;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,UACtC;AAED,wBAAgB,6BAA6B,CAAC,aAAa,EAAE,MAAM,eAC9C;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,UACtC;AAED,wBAAgB,8BAA8B,CAAC,aAAa,EAAE,MAAM,eAC/C,GAAG,UACvB;AAED,wBAAgB,2BAA2B,CAAC,aAAa,EAAE,MAAM,cAC7C,GAAG,UACtB;AAED,wBAAgB,4BAA4B,eAG3C;AAGD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,cAK7C;AAED,wBAAgB,UAAU,CAAC,SAAS,EAAE,GAAG;;;EAKxC;AAGD,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,SAAI,UAWtD"}
@@ -1,3 +1,4 @@
1
+ import { log } from '@vitessce/globals';
1
2
  // Originally in src/components/utils.js
2
3
  export const DEFAULT_DARK_COLOR = [50, 50, 50];
3
4
  export const DEFAULT_LIGHT_COLOR = [200, 200, 200];
@@ -72,22 +73,22 @@ export const COLORMAP_OPTIONS = [
72
73
  ];
73
74
  export const DEFAULT_GL_OPTIONS = { webgl2: true };
74
75
  export function createDefaultUpdateStatus(componentName) {
75
- return (message) => console.warn(`${componentName} updateStatus: ${message}`);
76
+ return (message) => log.warn(`${componentName} updateStatus: ${message}`);
76
77
  }
77
78
  export function createDefaultUpdateCellsSelection(componentName) {
78
- return (cellsSelection) => console.warn(`${componentName} updateCellsSelection: ${cellsSelection}`);
79
+ return (cellsSelection) => log.warn(`${componentName} updateCellsSelection: ${cellsSelection}`);
79
80
  }
80
81
  export function createDefaultUpdateCellsHover(componentName) {
81
- return (hoverInfo) => console.warn(`${componentName} updateCellsHover: ${hoverInfo.cellId}`);
82
+ return (hoverInfo) => log.warn(`${componentName} updateCellsHover: ${hoverInfo.cellId}`);
82
83
  }
83
84
  export function createDefaultUpdateGenesHover(componentName) {
84
- return (hoverInfo) => console.warn(`${componentName} updateGenesHover: ${hoverInfo.geneId}`);
85
+ return (hoverInfo) => log.warn(`${componentName} updateGenesHover: ${hoverInfo.geneId}`);
85
86
  }
86
87
  export function createDefaultUpdateTracksHover(componentName) {
87
- return (hoverInfo) => console.warn(`${componentName} updateTracksHover: ${hoverInfo}`);
88
+ return (hoverInfo) => log.warn(`${componentName} updateTracksHover: ${hoverInfo}`);
88
89
  }
89
90
  export function createDefaultUpdateViewInfo(componentName) {
90
- return (viewInfo) => console.warn(`${componentName} updateViewInfo: ${viewInfo}`);
91
+ return (viewInfo) => log.warn(`${componentName} updateViewInfo: ${viewInfo}`);
91
92
  }
92
93
  export function createDefaultClearPleaseWait() {
93
94
  // eslint-disable-next-line @typescript-eslint/no-empty-function
@@ -1,4 +1,4 @@
1
- export { commaNumber, capitalize, pluralize, cleanFeatureId, getLongestString, getNextScope, getNextScopeNumeric, createPrefixedGetNextScopeNumeric, getInitialCoordinationScopePrefix, getInitialCoordinationScopeName, } from './root.js';
1
+ export { commaNumber, capitalize, pluralize, cleanFeatureId, getLongestString, getNextScope, getNextScopeNumeric, createPrefixedGetNextScopeNumeric, getInitialCoordinationScopePrefix, getInitialCoordinationScopeName, unnestMap, } from './root.js';
2
2
  export { DEFAULT_DARK_COLOR, DEFAULT_LIGHT_COLOR, getDefaultColor, PALETTE, VIEWER_PALETTE, PATHOLOGY_PALETTE, LARGE_PATHOLOGY_PALETTE, COLORMAP_OPTIONS, DEFAULT_GL_OPTIONS, createDefaultUpdateStatus, createDefaultUpdateCellsSelection, createDefaultUpdateCellsHover, createDefaultUpdateGenesHover, createDefaultUpdateTracksHover, createDefaultUpdateViewInfo, createDefaultClearPleaseWait, copyUint8Array, asEsModule, formatBytes, } from './components.js';
3
3
  export { getValueTransformFunction, VALUE_TRANSFORM_OPTIONS, } from './gating.js';
4
4
  export { default as Pool } from './Pool.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,WAAW,EACX,UAAU,EACV,SAAS,EACT,cAAc,EACd,gBAAgB,EAChB,YAAY,EACZ,mBAAmB,EACnB,iCAAiC,EACjC,iCAAiC,EACjC,+BAA+B,GAChC,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,OAAO,EACP,cAAc,EACd,iBAAiB,EACjB,uBAAuB,EACvB,gBAAgB,EAChB,kBAAkB,EAClB,yBAAyB,EACzB,iCAAiC,EACjC,6BAA6B,EAC7B,6BAA6B,EAC7B,8BAA8B,EAC9B,2BAA2B,EAC3B,4BAA4B,EAC5B,cAAc,EACd,UAAU,EACV,WAAW,GACZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,OAAO,IAAI,IAAI,EAAE,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,WAAW,EACX,UAAU,EACV,SAAS,EACT,cAAc,EACd,gBAAgB,EAChB,YAAY,EACZ,mBAAmB,EACnB,iCAAiC,EACjC,iCAAiC,EACjC,+BAA+B,EAC/B,SAAS,GACV,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,OAAO,EACP,cAAc,EACd,iBAAiB,EACjB,uBAAuB,EACvB,gBAAgB,EAChB,kBAAkB,EAClB,yBAAyB,EACzB,iCAAiC,EACjC,6BAA6B,EAC7B,6BAA6B,EAC7B,8BAA8B,EAC9B,2BAA2B,EAC3B,4BAA4B,EAC5B,cAAc,EACd,UAAU,EACV,WAAW,GACZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,OAAO,IAAI,IAAI,EAAE,MAAM,WAAW,CAAC"}
package/dist-tsc/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // eslint-disable-next-line react-refresh/only-export-components
2
- export { commaNumber, capitalize, pluralize, cleanFeatureId, getLongestString, getNextScope, getNextScopeNumeric, createPrefixedGetNextScopeNumeric, getInitialCoordinationScopePrefix, getInitialCoordinationScopeName, } from './root.js';
2
+ export { commaNumber, capitalize, pluralize, cleanFeatureId, getLongestString, getNextScope, getNextScopeNumeric, createPrefixedGetNextScopeNumeric, getInitialCoordinationScopePrefix, getInitialCoordinationScopeName, unnestMap, } from './root.js';
3
3
  // eslint-disable-next-line react-refresh/only-export-components
4
4
  export { DEFAULT_DARK_COLOR, DEFAULT_LIGHT_COLOR, getDefaultColor, PALETTE, VIEWER_PALETTE, PATHOLOGY_PALETTE, LARGE_PATHOLOGY_PALETTE, COLORMAP_OPTIONS, DEFAULT_GL_OPTIONS, createDefaultUpdateStatus, createDefaultUpdateCellsSelection, createDefaultUpdateCellsHover, createDefaultUpdateGenesHover, createDefaultUpdateTracksHover, createDefaultUpdateViewInfo, createDefaultClearPleaseWait, copyUint8Array, asEsModule, formatBytes, } from './components.js';
5
5
  export { getValueTransformFunction, VALUE_TRANSFORM_OPTIONS, } from './gating.js';
@@ -71,4 +71,15 @@ export declare function getInitialCoordinationScopePrefix(datasetUid: string, da
71
71
  * like "init_<datasetUid>_<dataType>_<i>".
72
72
  */
73
73
  export declare function getInitialCoordinationScopeName(datasetUid: string, dataType: string, i?: number | null): string;
74
+ /**
75
+ * Convert a (potentially nested) InternMap or Map
76
+ * to a flat array which can be passed to d3-group
77
+ * to enable an alternative nesting strategy.
78
+ * @param map The InternMap or Map to flatten.
79
+ * @param keys An array of new keys [levelZeroKey, levelOneKey, valueKey]
80
+ * with one more than the number of Map levels.
81
+ * @param aggFunc Optionally, an aggregation function to apply to leaves.
82
+ * @returns The flattened array.
83
+ */
84
+ export declare function unnestMap(map: Map<any, any>, keys: string[], aggFunc?: ((d: any) => any)): object[];
74
85
  //# sourceMappingURL=root.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"root.d.ts","sourceRoot":"","sources":["../src/root.ts"],"names":[],"mappings":"AAOA,wBAAgB,WAAW,CAAC,CAAC,EAAE,MAAM,UAGpC;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,UAE7C;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,MAAM,GAAG,IAAW,OAElE;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,UAMjD;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,UAMjD;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,UAqChD;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,UAQvD;AAED;;;;GAIG;AACH,wBAAgB,iCAAiC,CAAC,MAAM,EAAE,MAAM,gBAC1C,MAAM,EAAE,YAS7B;AAED;;;;;;;GAOG;AACH,wBAAgB,iCAAiC,CAC/C,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,UAGrC;AAED;;;;;;;;;GASG;AACH,wBAAgB,+BAA+B,CAC7C,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,GAAE,MAAM,GAAG,IAAW,UAI9D"}
1
+ {"version":3,"file":"root.d.ts","sourceRoot":"","sources":["../src/root.ts"],"names":[],"mappings":"AAOA,wBAAgB,WAAW,CAAC,CAAC,EAAE,MAAM,UAGpC;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,UAE7C;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,MAAM,GAAG,IAAW,OAElE;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,UAMjD;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,UAMjD;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,UAqChD;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,UAQvD;AAED;;;;GAIG;AACH,wBAAgB,iCAAiC,CAAC,MAAM,EAAE,MAAM,gBAC1C,MAAM,EAAE,YAS7B;AAED;;;;;;;GAOG;AACH,wBAAgB,iCAAiC,CAC/C,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,UAGrC;AAED;;;;;;;;;GASG;AACH,wBAAgB,+BAA+B,CAC7C,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,GAAE,MAAM,GAAG,IAAW,UAI9D;AAID;;;;;;;;;GASG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,EAClB,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,GAAG,CAAC,GAC1B,MAAM,EAAE,CAmBV"}
package/dist-tsc/root.js CHANGED
@@ -150,3 +150,34 @@ export function getInitialCoordinationScopeName(datasetUid, dataType, i = null)
150
150
  const prefix = getInitialCoordinationScopePrefix(datasetUid, dataType);
151
151
  return `${prefix}${i === null ? 0 : i}`;
152
152
  }
153
+ const identityFunc = ((d) => d);
154
+ /**
155
+ * Convert a (potentially nested) InternMap or Map
156
+ * to a flat array which can be passed to d3-group
157
+ * to enable an alternative nesting strategy.
158
+ * @param map The InternMap or Map to flatten.
159
+ * @param keys An array of new keys [levelZeroKey, levelOneKey, valueKey]
160
+ * with one more than the number of Map levels.
161
+ * @param aggFunc Optionally, an aggregation function to apply to leaves.
162
+ * @returns The flattened array.
163
+ */
164
+ export function unnestMap(map, keys, aggFunc) {
165
+ if (keys.length < 2) {
166
+ throw new Error('Insufficient number of keys passed to flattenInternMap');
167
+ }
168
+ const aggFuncToUse = (!aggFunc ? identityFunc : aggFunc);
169
+ return Array.from(map.entries()).flatMap(([k, v]) => {
170
+ if (v instanceof Map) {
171
+ const keysWithoutFirst = [...keys];
172
+ keysWithoutFirst.splice(0, 1);
173
+ return unnestMap(v, keysWithoutFirst, aggFuncToUse).map(childObj => ({
174
+ [keys[0]]: k,
175
+ ...childObj,
176
+ }));
177
+ }
178
+ return {
179
+ [keys[0]]: k,
180
+ [keys[1]]: aggFuncToUse(v),
181
+ };
182
+ });
183
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=root.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"root.test.d.ts","sourceRoot":"","sources":["../src/root.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,301 @@
1
+ /* eslint-disable camelcase */
2
+ import { describe, expect, it } from 'vitest';
3
+ import { group as d3_group, rollup as d3_rollup, index as d3_index, } from 'd3-array';
4
+ import { unnestMap } from './root.js';
5
+ // Reference: https://observablehq.com/@d3/d3-group
6
+ const athletes = [
7
+ { name: 'Floyd Mayweather', sport: 'Boxing', nation: 'United States', earnings: 285 },
8
+ { name: 'Lionel Messi', sport: 'Soccer', nation: 'Argentina', earnings: 111 },
9
+ { name: 'Cristiano Ronaldo', sport: 'Soccer', nation: 'Portugal', earnings: 108 },
10
+ { name: 'Conor McGregor', sport: 'MMA', nation: 'Ireland', earnings: 99 },
11
+ { name: 'Neymar', sport: 'Soccer', nation: 'Brazil', earnings: 90 },
12
+ { name: 'LeBron James', sport: 'Basketball', nation: 'United States', earnings: 85.5 },
13
+ { name: 'Roger Federer', sport: 'Tennis', nation: 'Switzerland', earnings: 77.2 },
14
+ { name: 'Stephen Curry', sport: 'Basketball', nation: 'United States', earnings: 76.9 },
15
+ { name: 'Matt Ryan', sport: 'Football', nation: 'United States', earnings: 67.3 },
16
+ { name: 'Matthew Stafford', sport: 'Football', nation: 'United States', earnings: 59.5 },
17
+ ];
18
+ const athletesBySport = d3_group(athletes, d => d.sport);
19
+ const athletesBySportAndNation = d3_group(athletes, d => d.sport, d => d.nation);
20
+ const athletesByNationAndSport = d3_group(athletes, d => d.nation, d => d.sport);
21
+ describe('root.ts', () => {
22
+ describe('unnestMap works as expected', () => {
23
+ it('Can flatten a Map with one level', () => {
24
+ const m = new Map([
25
+ ['Boxing', 1],
26
+ ['Soccer', 2],
27
+ ['MMA', 3],
28
+ ['Basketball', 50],
29
+ ]);
30
+ expect(unnestMap(m, ['sport', 'value'])).toEqual([
31
+ { sport: 'Boxing', value: 1 },
32
+ { sport: 'Soccer', value: 2 },
33
+ { sport: 'MMA', value: 3 },
34
+ { sport: 'Basketball', value: 50 },
35
+ ]);
36
+ });
37
+ it('Can flatten a nested Map with one level', () => {
38
+ expect(unnestMap(athletesBySport, ['sport', 'value'])).toEqual([
39
+ {
40
+ sport: 'Boxing',
41
+ value: [
42
+ {
43
+ name: 'Floyd Mayweather',
44
+ sport: 'Boxing',
45
+ nation: 'United States',
46
+ earnings: 285,
47
+ },
48
+ ],
49
+ },
50
+ {
51
+ sport: 'Soccer',
52
+ value: [
53
+ {
54
+ name: 'Lionel Messi',
55
+ sport: 'Soccer',
56
+ nation: 'Argentina',
57
+ earnings: 111,
58
+ },
59
+ {
60
+ name: 'Cristiano Ronaldo',
61
+ sport: 'Soccer',
62
+ nation: 'Portugal',
63
+ earnings: 108,
64
+ },
65
+ {
66
+ name: 'Neymar',
67
+ sport: 'Soccer',
68
+ nation: 'Brazil',
69
+ earnings: 90,
70
+ },
71
+ ],
72
+ },
73
+ {
74
+ sport: 'MMA',
75
+ value: [
76
+ {
77
+ name: 'Conor McGregor',
78
+ sport: 'MMA',
79
+ nation: 'Ireland',
80
+ earnings: 99,
81
+ },
82
+ ],
83
+ },
84
+ {
85
+ sport: 'Basketball',
86
+ value: [
87
+ {
88
+ name: 'LeBron James',
89
+ sport: 'Basketball',
90
+ nation: 'United States',
91
+ earnings: 85.5,
92
+ },
93
+ {
94
+ name: 'Stephen Curry',
95
+ sport: 'Basketball',
96
+ nation: 'United States',
97
+ earnings: 76.9,
98
+ },
99
+ ],
100
+ },
101
+ {
102
+ sport: 'Tennis',
103
+ value: [
104
+ {
105
+ name: 'Roger Federer',
106
+ sport: 'Tennis',
107
+ nation: 'Switzerland',
108
+ earnings: 77.2,
109
+ },
110
+ ],
111
+ },
112
+ {
113
+ sport: 'Football',
114
+ value: [
115
+ {
116
+ name: 'Matt Ryan',
117
+ sport: 'Football',
118
+ nation: 'United States',
119
+ earnings: 67.3,
120
+ },
121
+ {
122
+ name: 'Matthew Stafford',
123
+ sport: 'Football',
124
+ nation: 'United States',
125
+ earnings: 59.5,
126
+ },
127
+ ],
128
+ },
129
+ ]);
130
+ });
131
+ it('Can flatten a nested Map with two levels', () => {
132
+ expect(unnestMap(athletesBySportAndNation, ['sport', 'nation', 'value'])).toEqual([
133
+ {
134
+ sport: 'Boxing',
135
+ nation: 'United States',
136
+ value: [
137
+ {
138
+ name: 'Floyd Mayweather',
139
+ sport: 'Boxing',
140
+ nation: 'United States',
141
+ earnings: 285,
142
+ },
143
+ ],
144
+ },
145
+ {
146
+ sport: 'Soccer',
147
+ nation: 'Argentina',
148
+ value: [
149
+ {
150
+ name: 'Lionel Messi',
151
+ sport: 'Soccer',
152
+ nation: 'Argentina',
153
+ earnings: 111,
154
+ },
155
+ ],
156
+ },
157
+ {
158
+ sport: 'Soccer',
159
+ nation: 'Portugal',
160
+ value: [
161
+ {
162
+ name: 'Cristiano Ronaldo',
163
+ sport: 'Soccer',
164
+ nation: 'Portugal',
165
+ earnings: 108,
166
+ },
167
+ ],
168
+ },
169
+ {
170
+ sport: 'Soccer',
171
+ nation: 'Brazil',
172
+ value: [
173
+ {
174
+ name: 'Neymar',
175
+ sport: 'Soccer',
176
+ nation: 'Brazil',
177
+ earnings: 90,
178
+ },
179
+ ],
180
+ },
181
+ {
182
+ sport: 'MMA',
183
+ nation: 'Ireland',
184
+ value: [
185
+ {
186
+ name: 'Conor McGregor',
187
+ sport: 'MMA',
188
+ nation: 'Ireland',
189
+ earnings: 99,
190
+ },
191
+ ],
192
+ },
193
+ {
194
+ sport: 'Basketball',
195
+ nation: 'United States',
196
+ value: [
197
+ {
198
+ name: 'LeBron James',
199
+ sport: 'Basketball',
200
+ nation: 'United States',
201
+ earnings: 85.5,
202
+ },
203
+ {
204
+ name: 'Stephen Curry',
205
+ sport: 'Basketball',
206
+ nation: 'United States',
207
+ earnings: 76.9,
208
+ },
209
+ ],
210
+ },
211
+ {
212
+ sport: 'Tennis',
213
+ nation: 'Switzerland',
214
+ value: [
215
+ {
216
+ name: 'Roger Federer',
217
+ sport: 'Tennis',
218
+ nation: 'Switzerland',
219
+ earnings: 77.2,
220
+ },
221
+ ],
222
+ },
223
+ {
224
+ sport: 'Football',
225
+ nation: 'United States',
226
+ value: [
227
+ {
228
+ name: 'Matt Ryan',
229
+ sport: 'Football',
230
+ nation: 'United States',
231
+ earnings: 67.3,
232
+ },
233
+ {
234
+ name: 'Matthew Stafford',
235
+ sport: 'Football',
236
+ nation: 'United States',
237
+ earnings: 59.5,
238
+ },
239
+ ],
240
+ },
241
+ ]);
242
+ });
243
+ it('Can flatten a nested Map with one level and an aggregation function', () => {
244
+ expect(unnestMap(athletesBySport, ['sport', 'value'], (arr) => arr.length)).toEqual([
245
+ {
246
+ sport: 'Boxing',
247
+ value: 1,
248
+ },
249
+ {
250
+ sport: 'Soccer',
251
+ value: 3,
252
+ },
253
+ {
254
+ sport: 'MMA',
255
+ value: 1,
256
+ },
257
+ {
258
+ sport: 'Basketball',
259
+ value: 2,
260
+ },
261
+ {
262
+ sport: 'Tennis',
263
+ value: 1,
264
+ },
265
+ {
266
+ sport: 'Football',
267
+ value: 2,
268
+ },
269
+ ]);
270
+ });
271
+ it('Works with d3.group to switch the order of the hierarchy levels', () => {
272
+ const unnestResult = (unnestMap(athletesBySportAndNation, ['sport', 'nation', 'value'])
273
+ .flatMap((v) => v.value));
274
+ const nationThenSport = d3_group(unnestResult, (d) => d.nation, (d) => d.sport);
275
+ expect(nationThenSport).toEqual(athletesByNationAndSport);
276
+ });
277
+ it('Works with d3.index to go from Map -> array of objects -> Map', () => {
278
+ const m = new Map([
279
+ ['Boxing', 1],
280
+ ['Soccer', 2],
281
+ ['MMA', 3],
282
+ ['Basketball', 50],
283
+ ]);
284
+ expect(unnestMap(d3_index(unnestMap(m, ['sport', 'value']), (d) => d.sport), ['sport', 'value'], (d) => d.value)).toEqual([
285
+ { sport: 'Boxing', value: 1 },
286
+ { sport: 'Soccer', value: 2 },
287
+ { sport: 'MMA', value: 3 },
288
+ { sport: 'Basketball', value: 50 },
289
+ ]);
290
+ });
291
+ it('Works with d3.rollup to go from Map -> array of objects -> Map', () => {
292
+ const m = new Map([
293
+ ['Boxing', 1],
294
+ ['Soccer', 2],
295
+ ['MMA', 3],
296
+ ['Basketball', 50],
297
+ ]);
298
+ expect(Array.from(d3_rollup(unnestMap(m, ['sport', 'value']), (D) => D[0].value, (d) => d.sport).entries())).toEqual(Array.from(m.entries()));
299
+ });
300
+ });
301
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitessce/utils",
3
- "version": "3.5.5",
3
+ "version": "3.5.7",
4
4
  "author": "HIDIVE Lab at HMS",
5
5
  "homepage": "http://vitessce.io",
6
6
  "repository": {
@@ -19,7 +19,9 @@
19
19
  "bowser": "^2.11.0",
20
20
  "lodash-es": "^4.17.21",
21
21
  "lz-string": "^1.4.4",
22
- "pluralize": "^8.0.0"
22
+ "pluralize": "^8.0.0",
23
+ "d3-array": "^2.4.0",
24
+ "@vitessce/globals": "3.5.7"
23
25
  },
24
26
  "scripts": {
25
27
  "bundle": "pnpm exec vite build -c ../../../scripts/vite.config.js",
package/src/components.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { log } from '@vitessce/globals';
2
+
1
3
  // Originally in src/components/utils.js
2
4
  export const DEFAULT_DARK_COLOR = [50, 50, 50];
3
5
  export const DEFAULT_LIGHT_COLOR = [200, 200, 200];
@@ -80,27 +82,27 @@ export const COLORMAP_OPTIONS = [
80
82
  export const DEFAULT_GL_OPTIONS = { webgl2: true };
81
83
 
82
84
  export function createDefaultUpdateStatus(componentName: string) {
83
- return (message: string) => console.warn(`${componentName} updateStatus: ${message}`);
85
+ return (message: string) => log.warn(`${componentName} updateStatus: ${message}`);
84
86
  }
85
87
 
86
88
  export function createDefaultUpdateCellsSelection(componentName: string) {
87
- return (cellsSelection: any) => console.warn(`${componentName} updateCellsSelection: ${cellsSelection}`);
89
+ return (cellsSelection: any) => log.warn(`${componentName} updateCellsSelection: ${cellsSelection}`);
88
90
  }
89
91
 
90
92
  export function createDefaultUpdateCellsHover(componentName: string) {
91
- return (hoverInfo: { cellId: string }) => console.warn(`${componentName} updateCellsHover: ${hoverInfo.cellId}`);
93
+ return (hoverInfo: { cellId: string }) => log.warn(`${componentName} updateCellsHover: ${hoverInfo.cellId}`);
92
94
  }
93
95
 
94
96
  export function createDefaultUpdateGenesHover(componentName: string) {
95
- return (hoverInfo: { geneId: string }) => console.warn(`${componentName} updateGenesHover: ${hoverInfo.geneId}`);
97
+ return (hoverInfo: { geneId: string }) => log.warn(`${componentName} updateGenesHover: ${hoverInfo.geneId}`);
96
98
  }
97
99
 
98
100
  export function createDefaultUpdateTracksHover(componentName: string) {
99
- return (hoverInfo: any) => console.warn(`${componentName} updateTracksHover: ${hoverInfo}`);
101
+ return (hoverInfo: any) => log.warn(`${componentName} updateTracksHover: ${hoverInfo}`);
100
102
  }
101
103
 
102
104
  export function createDefaultUpdateViewInfo(componentName: string) {
103
- return (viewInfo: any) => console.warn(`${componentName} updateViewInfo: ${viewInfo}`);
105
+ return (viewInfo: any) => log.warn(`${componentName} updateViewInfo: ${viewInfo}`);
104
106
  }
105
107
 
106
108
  export function createDefaultClearPleaseWait() {
package/src/index.ts CHANGED
@@ -10,6 +10,7 @@ export {
10
10
  createPrefixedGetNextScopeNumeric,
11
11
  getInitialCoordinationScopePrefix,
12
12
  getInitialCoordinationScopeName,
13
+ unnestMap,
13
14
  } from './root.js';
14
15
  // eslint-disable-next-line react-refresh/only-export-components
15
16
  export {
@@ -0,0 +1,325 @@
1
+ /* eslint-disable camelcase */
2
+ import { describe, expect, it } from 'vitest';
3
+ import {
4
+ group as d3_group,
5
+ rollup as d3_rollup,
6
+ index as d3_index,
7
+ } from 'd3-array';
8
+ import { unnestMap } from './root.js';
9
+
10
+ // Reference: https://observablehq.com/@d3/d3-group
11
+ const athletes = [
12
+ { name: 'Floyd Mayweather', sport: 'Boxing', nation: 'United States', earnings: 285 },
13
+ { name: 'Lionel Messi', sport: 'Soccer', nation: 'Argentina', earnings: 111 },
14
+ { name: 'Cristiano Ronaldo', sport: 'Soccer', nation: 'Portugal', earnings: 108 },
15
+ { name: 'Conor McGregor', sport: 'MMA', nation: 'Ireland', earnings: 99 },
16
+ { name: 'Neymar', sport: 'Soccer', nation: 'Brazil', earnings: 90 },
17
+ { name: 'LeBron James', sport: 'Basketball', nation: 'United States', earnings: 85.5 },
18
+ { name: 'Roger Federer', sport: 'Tennis', nation: 'Switzerland', earnings: 77.2 },
19
+ { name: 'Stephen Curry', sport: 'Basketball', nation: 'United States', earnings: 76.9 },
20
+ { name: 'Matt Ryan', sport: 'Football', nation: 'United States', earnings: 67.3 },
21
+ { name: 'Matthew Stafford', sport: 'Football', nation: 'United States', earnings: 59.5 },
22
+ ];
23
+
24
+ const athletesBySport = d3_group(athletes, d => d.sport);
25
+ const athletesBySportAndNation = d3_group(athletes, d => d.sport, d => d.nation);
26
+ const athletesByNationAndSport = d3_group(athletes, d => d.nation, d => d.sport);
27
+
28
+ describe('root.ts', () => {
29
+ describe('unnestMap works as expected', () => {
30
+ it('Can flatten a Map with one level', () => {
31
+ const m = new Map([
32
+ ['Boxing', 1],
33
+ ['Soccer', 2],
34
+ ['MMA', 3],
35
+ ['Basketball', 50],
36
+ ]);
37
+ expect(unnestMap(m, ['sport', 'value'])).toEqual([
38
+ { sport: 'Boxing', value: 1 },
39
+ { sport: 'Soccer', value: 2 },
40
+ { sport: 'MMA', value: 3 },
41
+ { sport: 'Basketball', value: 50 },
42
+ ]);
43
+ });
44
+ it('Can flatten a nested Map with one level', () => {
45
+ expect(unnestMap(athletesBySport, ['sport', 'value'])).toEqual([
46
+ {
47
+ sport: 'Boxing',
48
+ value: [
49
+ {
50
+ name: 'Floyd Mayweather',
51
+ sport: 'Boxing',
52
+ nation: 'United States',
53
+ earnings: 285,
54
+ },
55
+ ],
56
+ },
57
+ {
58
+ sport: 'Soccer',
59
+ value: [
60
+ {
61
+ name: 'Lionel Messi',
62
+ sport: 'Soccer',
63
+ nation: 'Argentina',
64
+ earnings: 111,
65
+ },
66
+ {
67
+ name: 'Cristiano Ronaldo',
68
+ sport: 'Soccer',
69
+ nation: 'Portugal',
70
+ earnings: 108,
71
+ },
72
+ {
73
+ name: 'Neymar',
74
+ sport: 'Soccer',
75
+ nation: 'Brazil',
76
+ earnings: 90,
77
+ },
78
+ ],
79
+ },
80
+ {
81
+ sport: 'MMA',
82
+ value: [
83
+ {
84
+ name: 'Conor McGregor',
85
+ sport: 'MMA',
86
+ nation: 'Ireland',
87
+ earnings: 99,
88
+ },
89
+ ],
90
+ },
91
+ {
92
+ sport: 'Basketball',
93
+ value: [
94
+ {
95
+ name: 'LeBron James',
96
+ sport: 'Basketball',
97
+ nation: 'United States',
98
+ earnings: 85.5,
99
+ },
100
+ {
101
+ name: 'Stephen Curry',
102
+ sport: 'Basketball',
103
+ nation: 'United States',
104
+ earnings: 76.9,
105
+ },
106
+ ],
107
+ },
108
+ {
109
+ sport: 'Tennis',
110
+ value: [
111
+ {
112
+ name: 'Roger Federer',
113
+ sport: 'Tennis',
114
+ nation: 'Switzerland',
115
+ earnings: 77.2,
116
+ },
117
+ ],
118
+ },
119
+ {
120
+ sport: 'Football',
121
+ value: [
122
+ {
123
+ name: 'Matt Ryan',
124
+ sport: 'Football',
125
+ nation: 'United States',
126
+ earnings: 67.3,
127
+ },
128
+ {
129
+ name: 'Matthew Stafford',
130
+ sport: 'Football',
131
+ nation: 'United States',
132
+ earnings: 59.5,
133
+ },
134
+ ],
135
+ },
136
+ ]);
137
+ });
138
+ it('Can flatten a nested Map with two levels', () => {
139
+ expect(unnestMap(athletesBySportAndNation, ['sport', 'nation', 'value'])).toEqual([
140
+ {
141
+ sport: 'Boxing',
142
+ nation: 'United States',
143
+ value: [
144
+ {
145
+ name: 'Floyd Mayweather',
146
+ sport: 'Boxing',
147
+ nation: 'United States',
148
+ earnings: 285,
149
+ },
150
+ ],
151
+ },
152
+ {
153
+ sport: 'Soccer',
154
+ nation: 'Argentina',
155
+ value: [
156
+ {
157
+ name: 'Lionel Messi',
158
+ sport: 'Soccer',
159
+ nation: 'Argentina',
160
+ earnings: 111,
161
+ },
162
+ ],
163
+ },
164
+ {
165
+ sport: 'Soccer',
166
+ nation: 'Portugal',
167
+ value: [
168
+ {
169
+ name: 'Cristiano Ronaldo',
170
+ sport: 'Soccer',
171
+ nation: 'Portugal',
172
+ earnings: 108,
173
+ },
174
+ ],
175
+ },
176
+ {
177
+ sport: 'Soccer',
178
+ nation: 'Brazil',
179
+ value: [
180
+ {
181
+ name: 'Neymar',
182
+ sport: 'Soccer',
183
+ nation: 'Brazil',
184
+ earnings: 90,
185
+ },
186
+ ],
187
+ },
188
+ {
189
+ sport: 'MMA',
190
+ nation: 'Ireland',
191
+ value: [
192
+ {
193
+ name: 'Conor McGregor',
194
+ sport: 'MMA',
195
+ nation: 'Ireland',
196
+ earnings: 99,
197
+ },
198
+ ],
199
+ },
200
+ {
201
+ sport: 'Basketball',
202
+ nation: 'United States',
203
+ value: [
204
+ {
205
+ name: 'LeBron James',
206
+ sport: 'Basketball',
207
+ nation: 'United States',
208
+ earnings: 85.5,
209
+ },
210
+ {
211
+ name: 'Stephen Curry',
212
+ sport: 'Basketball',
213
+ nation: 'United States',
214
+ earnings: 76.9,
215
+ },
216
+ ],
217
+ },
218
+ {
219
+ sport: 'Tennis',
220
+ nation: 'Switzerland',
221
+ value: [
222
+ {
223
+ name: 'Roger Federer',
224
+ sport: 'Tennis',
225
+ nation: 'Switzerland',
226
+ earnings: 77.2,
227
+ },
228
+ ],
229
+ },
230
+ {
231
+ sport: 'Football',
232
+ nation: 'United States',
233
+ value: [
234
+ {
235
+ name: 'Matt Ryan',
236
+ sport: 'Football',
237
+ nation: 'United States',
238
+ earnings: 67.3,
239
+ },
240
+ {
241
+ name: 'Matthew Stafford',
242
+ sport: 'Football',
243
+ nation: 'United States',
244
+ earnings: 59.5,
245
+ },
246
+ ],
247
+ },
248
+ ]);
249
+ });
250
+ it('Can flatten a nested Map with one level and an aggregation function', () => {
251
+ expect(unnestMap(athletesBySport, ['sport', 'value'], (arr: any[]) => arr.length)).toEqual([
252
+ {
253
+ sport: 'Boxing',
254
+ value: 1,
255
+ },
256
+ {
257
+ sport: 'Soccer',
258
+ value: 3,
259
+ },
260
+ {
261
+ sport: 'MMA',
262
+ value: 1,
263
+ },
264
+ {
265
+ sport: 'Basketball',
266
+ value: 2,
267
+ },
268
+ {
269
+ sport: 'Tennis',
270
+ value: 1,
271
+ },
272
+ {
273
+ sport: 'Football',
274
+ value: 2,
275
+ },
276
+ ]);
277
+ });
278
+ it('Works with d3.group to switch the order of the hierarchy levels', () => {
279
+ const unnestResult = (
280
+ unnestMap(athletesBySportAndNation, ['sport', 'nation', 'value'])
281
+ .flatMap((v: any) => v.value)
282
+ );
283
+ const nationThenSport = d3_group(unnestResult, (d: any) => d.nation, (d: any) => d.sport);
284
+ expect(nationThenSport).toEqual(athletesByNationAndSport);
285
+ });
286
+ it('Works with d3.index to go from Map -> array of objects -> Map', () => {
287
+ const m = new Map([
288
+ ['Boxing', 1],
289
+ ['Soccer', 2],
290
+ ['MMA', 3],
291
+ ['Basketball', 50],
292
+ ]);
293
+ expect(
294
+ unnestMap(
295
+ d3_index(
296
+ unnestMap(m, ['sport', 'value']),
297
+ (d: any) => d.sport,
298
+ ),
299
+ ['sport', 'value'],
300
+ (d: any) => d.value,
301
+ ),
302
+ ).toEqual([
303
+ { sport: 'Boxing', value: 1 },
304
+ { sport: 'Soccer', value: 2 },
305
+ { sport: 'MMA', value: 3 },
306
+ { sport: 'Basketball', value: 50 },
307
+ ]);
308
+ });
309
+ it('Works with d3.rollup to go from Map -> array of objects -> Map', () => {
310
+ const m = new Map([
311
+ ['Boxing', 1],
312
+ ['Soccer', 2],
313
+ ['MMA', 3],
314
+ ['Basketball', 50],
315
+ ]);
316
+ expect(
317
+ Array.from(d3_rollup(
318
+ unnestMap(m, ['sport', 'value']),
319
+ (D: any) => D[0].value,
320
+ (d: any) => d.sport,
321
+ ).entries()),
322
+ ).toEqual(Array.from(m.entries()));
323
+ });
324
+ });
325
+ });
package/src/root.ts CHANGED
@@ -170,3 +170,40 @@ export function getInitialCoordinationScopeName(
170
170
  const prefix = getInitialCoordinationScopePrefix(datasetUid, dataType);
171
171
  return `${prefix}${i === null ? 0 : i}`;
172
172
  }
173
+
174
+ const identityFunc = ((d: any) => d);
175
+
176
+ /**
177
+ * Convert a (potentially nested) InternMap or Map
178
+ * to a flat array which can be passed to d3-group
179
+ * to enable an alternative nesting strategy.
180
+ * @param map The InternMap or Map to flatten.
181
+ * @param keys An array of new keys [levelZeroKey, levelOneKey, valueKey]
182
+ * with one more than the number of Map levels.
183
+ * @param aggFunc Optionally, an aggregation function to apply to leaves.
184
+ * @returns The flattened array.
185
+ */
186
+ export function unnestMap(
187
+ map: Map<any, any>,
188
+ keys: string[],
189
+ aggFunc?: ((d: any) => any),
190
+ ): object[] {
191
+ if (keys.length < 2) {
192
+ throw new Error('Insufficient number of keys passed to flattenInternMap');
193
+ }
194
+ const aggFuncToUse = (!aggFunc ? identityFunc : aggFunc);
195
+ return Array.from(map.entries()).flatMap(([k, v]) => {
196
+ if (v instanceof Map) {
197
+ const keysWithoutFirst = [...keys];
198
+ keysWithoutFirst.splice(0, 1);
199
+ return unnestMap(v, keysWithoutFirst, aggFuncToUse).map(childObj => ({
200
+ [keys[0]]: k,
201
+ ...childObj,
202
+ }));
203
+ }
204
+ return {
205
+ [keys[0]]: k,
206
+ [keys[1]]: aggFuncToUse(v),
207
+ };
208
+ });
209
+ }