SetIntersection.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * @author d98762625 [d98762625@gmail.com]
  3. * @copyright Crown Copyright 2018
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation";
  7. import OperationError from "../errors/OperationError";
  8. /**
  9. * Set Intersection operation
  10. */
  11. class SetIntersection extends Operation {
  12. /**
  13. * Set Intersection constructor
  14. */
  15. constructor() {
  16. super();
  17. this.name = "Set Intersection";
  18. this.module = "Default";
  19. this.description = "Calculates the intersection of two sets.";
  20. this.inputType = "string";
  21. this.outputType = "string";
  22. this.args = [
  23. {
  24. name: "Sample delimiter",
  25. type: "binaryString",
  26. value: "\\n\\n"
  27. },
  28. {
  29. name: "Item delimiter",
  30. type: "binaryString",
  31. value: ","
  32. },
  33. ];
  34. }
  35. /**
  36. * Validate input length
  37. *
  38. * @param {Object[]} sets
  39. * @throws {Error} if not two sets
  40. */
  41. validateSampleNumbers(sets) {
  42. if (!sets || (sets.length !== 2)) {
  43. throw new OperationError("Incorrect number of sets, perhaps you need to modify the sample delimiter or add more samples?");
  44. }
  45. }
  46. /**
  47. * Run the intersection operation
  48. *
  49. * @param {string} input
  50. * @param {Object[]} args
  51. * @returns {string}
  52. * @throws {OperationError}
  53. */
  54. run(input, args) {
  55. [this.sampleDelim, this.itemDelimiter] = args;
  56. const sets = input.split(this.sampleDelim);
  57. this.validateSampleNumbers(sets);
  58. return this.runIntersect(...sets.map(s => s.split(this.itemDelimiter)));
  59. }
  60. /**
  61. * Get the intersection of the two sets.
  62. *
  63. * @param {Object[]} a
  64. * @param {Object[]} b
  65. * @returns {Object[]}
  66. */
  67. runIntersect(a, b) {
  68. return a
  69. .filter((item) => {
  70. return b.indexOf(item) > -1;
  71. })
  72. .join(this.itemDelimiter);
  73. }
  74. }
  75. export default SetIntersection;