SetIntersection.mjs 2.0 KB

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