ConditionalJump.mjs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * @author n1474335 [n1474335@gmail.com]
  3. * @copyright Crown Copyright 2018
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation.mjs";
  7. import Dish from "../Dish.mjs";
  8. import { getLabelIndex } from "../lib/FlowControl.mjs";
  9. /**
  10. * Conditional Jump operation
  11. */
  12. class ConditionalJump extends Operation {
  13. /**
  14. * ConditionalJump constructor
  15. */
  16. constructor() {
  17. super();
  18. this.name = "Conditional Jump";
  19. this.flowControl = true;
  20. this.module = "Default";
  21. this.description = "Conditionally jump forwards or backwards to the specified Label based on whether the data matches the specified regular expression.";
  22. this.inputType = "string";
  23. this.outputType = "string";
  24. this.args = [
  25. {
  26. "name": "Match (regex)",
  27. "type": "string",
  28. "value": ""
  29. },
  30. {
  31. "name": "Invert match",
  32. "type": "boolean",
  33. "value": false
  34. },
  35. {
  36. "name": "Label name",
  37. "type": "shortString",
  38. "value": ""
  39. },
  40. {
  41. "name": "Maximum jumps (if jumping backwards)",
  42. "type": "number",
  43. "value": 10
  44. }
  45. ];
  46. }
  47. /**
  48. * @param {Object} state - The current state of the recipe.
  49. * @param {number} state.progress - The current position in the recipe.
  50. * @param {Dish} state.dish - The Dish being operated on.
  51. * @param {Operation[]} state.opList - The list of operations in the recipe.
  52. * @param {number} state.numJumps - The number of jumps taken so far.
  53. * @returns {Object} The updated state of the recipe.
  54. */
  55. async run(state) {
  56. const ings = state.opList[state.progress].ingValues,
  57. dish = state.dish,
  58. [regexStr, invert, label, maxJumps] = ings,
  59. jmpIndex = getLabelIndex(label, state);
  60. if (state.numJumps >= maxJumps || jmpIndex === -1) {
  61. state.numJumps = 0;
  62. return state;
  63. }
  64. if (regexStr !== "") {
  65. const str = await dish.get(Dish.STRING);
  66. const strMatch = str.search(regexStr) > -1;
  67. if (!invert && strMatch || invert && !strMatch) {
  68. state.progress = jmpIndex;
  69. state.numJumps++;
  70. }
  71. else {
  72. state.numJumps = 0;
  73. }
  74. }
  75. return state;
  76. }
  77. }
  78. export default ConditionalJump;