Sin descripción
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

functional.js 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.nullsafeVisitor = exports.mapObject = exports.partition = exports.assertExhaustive = exports.zipIn = exports.zip = exports.reduceFlat = exports.flatten = exports.flattenArray = exports.flattenObject = void 0;
  4. function* flattenObject(obj) {
  5. function* helper(path, obj) {
  6. for (const [k, v] of Object.entries(obj)) {
  7. if (typeof v !== "object" || v === null) {
  8. yield [[...path, k].join("."), v];
  9. }
  10. else {
  11. yield* helper([...path, k], v);
  12. }
  13. }
  14. }
  15. yield* helper([], obj);
  16. }
  17. exports.flattenObject = flattenObject;
  18. function* flattenArray(arr) {
  19. for (const val of arr) {
  20. if (Array.isArray(val)) {
  21. yield* flattenArray(val);
  22. }
  23. else {
  24. yield val;
  25. }
  26. }
  27. }
  28. exports.flattenArray = flattenArray;
  29. function flatten(objOrArr) {
  30. if (Array.isArray(objOrArr)) {
  31. return flattenArray(objOrArr);
  32. }
  33. else {
  34. return flattenObject(objOrArr);
  35. }
  36. }
  37. exports.flatten = flatten;
  38. function reduceFlat(accum, next) {
  39. return [...(accum || []), ...flatten([next])];
  40. }
  41. exports.reduceFlat = reduceFlat;
  42. function* zip(left, right) {
  43. if (left.length !== right.length) {
  44. throw new Error("Cannot zip between two lists of differen lengths");
  45. }
  46. for (let i = 0; i < left.length; i++) {
  47. yield [left[i], right[i]];
  48. }
  49. }
  50. exports.zip = zip;
  51. const zipIn = (other) => (elem, ndx) => {
  52. return [elem, other[ndx]];
  53. };
  54. exports.zipIn = zipIn;
  55. function assertExhaustive(val) {
  56. throw new Error(`Never has a value (${val}). This should be impossible`);
  57. }
  58. exports.assertExhaustive = assertExhaustive;
  59. function partition(arr, callbackFn) {
  60. return arr.reduce((acc, elem) => {
  61. acc[callbackFn(elem) ? 0 : 1].push(elem);
  62. return acc;
  63. }, [[], []]);
  64. }
  65. exports.partition = partition;
  66. function mapObject(input, transform) {
  67. const result = {};
  68. for (const [k, v] of Object.entries(input)) {
  69. result[k] = transform(v);
  70. }
  71. return result;
  72. }
  73. exports.mapObject = mapObject;
  74. const nullsafeVisitor = (func, ...rest) => (first) => {
  75. if (first === null) {
  76. return null;
  77. }
  78. return func(first, ...rest);
  79. };
  80. exports.nullsafeVisitor = nullsafeVisitor;