buildMatchFn.cjs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. exports.buildMatchFn = buildMatchFn;
  3. function buildMatchFn(args) {
  4. return (string, options = {}) => {
  5. const width = options.width;
  6. const matchPattern =
  7. (width && args.matchPatterns[width]) ||
  8. args.matchPatterns[args.defaultMatchWidth];
  9. const matchResult = string.match(matchPattern);
  10. if (!matchResult) {
  11. return null;
  12. }
  13. const matchedString = matchResult[0];
  14. const parsePatterns =
  15. (width && args.parsePatterns[width]) ||
  16. args.parsePatterns[args.defaultParseWidth];
  17. const key = Array.isArray(parsePatterns)
  18. ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString))
  19. : // [TODO] -- I challenge you to fix the type
  20. findKey(parsePatterns, (pattern) => pattern.test(matchedString));
  21. let value;
  22. value = args.valueCallback ? args.valueCallback(key) : key;
  23. value = options.valueCallback
  24. ? // [TODO] -- I challenge you to fix the type
  25. options.valueCallback(value)
  26. : value;
  27. const rest = string.slice(matchedString.length);
  28. return { value, rest };
  29. };
  30. }
  31. function findKey(object, predicate) {
  32. for (const key in object) {
  33. if (
  34. Object.prototype.hasOwnProperty.call(object, key) &&
  35. predicate(object[key])
  36. ) {
  37. return key;
  38. }
  39. }
  40. return undefined;
  41. }
  42. function findIndex(array, predicate) {
  43. for (let key = 0; key < array.length; key++) {
  44. if (predicate(array[key])) {
  45. return key;
  46. }
  47. }
  48. return undefined;
  49. }