NormaliseUnicode.mjs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @author Matthieu [m@tthieu.xyz]
  3. * @copyright Crown Copyright 2019
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation.mjs";
  7. import OperationError from "../errors/OperationError.mjs";
  8. import {UNICODE_NORMALISATION_FORMS} from "../lib/ChrEnc.mjs";
  9. import unorm from "unorm";
  10. /**
  11. * Normalise Unicode operation
  12. */
  13. class NormaliseUnicode extends Operation {
  14. /**
  15. * NormaliseUnicode constructor
  16. */
  17. constructor() {
  18. super();
  19. this.name = "Normalise Unicode";
  20. this.module = "Encodings";
  21. this.description = "Transform Unicode characters to one of the Normalisation Forms";
  22. this.infoURL = "https://wikipedia.org/wiki/Unicode_equivalence#Normal_forms";
  23. this.inputType = "string";
  24. this.outputType = "string";
  25. this.args = [
  26. {
  27. name: "Normal Form",
  28. type: "option",
  29. value: UNICODE_NORMALISATION_FORMS
  30. }
  31. ];
  32. }
  33. /**
  34. * @param {string} input
  35. * @param {Object[]} args
  36. * @returns {string}
  37. */
  38. run(input, args) {
  39. const [normalForm] = args;
  40. switch (normalForm) {
  41. case "NFD":
  42. return unorm.nfd(input);
  43. case "NFC":
  44. return unorm.nfc(input);
  45. case "NFKD":
  46. return unorm.nfkd(input);
  47. case "NFKC":
  48. return unorm.nfc(input);
  49. default:
  50. throw new OperationError("Unknown Normalisation Form");
  51. }
  52. }
  53. }
  54. export default NormaliseUnicode;