SetUnion.mjs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import Utils from "../Utils";
  2. import Operation from "../Operation";
  3. /**
  4. * Set Union operation
  5. */
  6. class SetUnion extends Operation {
  7. /**
  8. * Set Union constructor
  9. */
  10. constructor() {
  11. super();
  12. this.name = "Set Union";
  13. this.module = "Default";
  14. this.description = "Get the union of two sets";
  15. this.inputType = "string";
  16. this.outputType = "string";
  17. this.args = [
  18. {
  19. name: "Sample delimiter",
  20. type: "binaryString",
  21. value: Utils.escapeHtml("\\n\\n")
  22. },
  23. {
  24. name: "Item delimiter",
  25. type: "binaryString",
  26. value: ","
  27. },
  28. ];
  29. }
  30. /**
  31. * Validate input length
  32. * @param {Object[]} sets
  33. * @throws {Error} if not two sets
  34. */
  35. validateSampleNumbers(sets) {
  36. if (!sets || (sets.length !== 2)) {
  37. throw "Incorrect number of sets, perhaps you need to modify the sample delimiter or add more samples?";
  38. }
  39. }
  40. /**
  41. * Run the union operation
  42. * @param input
  43. * @param args
  44. */
  45. run(input, args) {
  46. [this.sampleDelim, this.itemDelimiter] = args;
  47. const sets = input.split(this.sampleDelim);
  48. try {
  49. this.validateSampleNumbers(sets);
  50. } catch (e) {
  51. return e;
  52. }
  53. return Utils.escapeHtml(this.runUnion(...sets.map(s => s.split(this.itemDelimiter))));
  54. }
  55. /**
  56. * Get the union of the two sets.
  57. *
  58. * @param {Object[]} a
  59. * @param {Object[]} b
  60. * @returns {Object[]}
  61. */
  62. runUnion(a, b) {
  63. const result = {};
  64. /**
  65. * Only add non-existing items
  66. * @param {Object} hash
  67. */
  68. const addUnique = (hash) => (item) => {
  69. if (!hash[item]) {
  70. hash[item] = true;
  71. }
  72. };
  73. a.map(addUnique(result));
  74. b.map(addUnique(result));
  75. return Object.keys(result).join(this.itemDelimiter);
  76. }
  77. }
  78. export default SetUnion;