index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = buildMatchFn;
  6. function buildMatchFn(args) {
  7. return function (dirtyString, dirtyOptions) {
  8. var string = String(dirtyString);
  9. var options = dirtyOptions || {};
  10. var width = options.width;
  11. var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
  12. var matchResult = string.match(matchPattern);
  13. if (!matchResult) {
  14. return null;
  15. }
  16. var matchedString = matchResult[0];
  17. var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
  18. var value;
  19. if (Object.prototype.toString.call(parsePatterns) === '[object Array]') {
  20. value = findIndex(parsePatterns, function (pattern) {
  21. return pattern.test(matchedString);
  22. });
  23. } else {
  24. value = findKey(parsePatterns, function (pattern) {
  25. return pattern.test(matchedString);
  26. });
  27. }
  28. value = args.valueCallback ? args.valueCallback(value) : value;
  29. value = options.valueCallback ? options.valueCallback(value) : value;
  30. return {
  31. value: value,
  32. rest: string.slice(matchedString.length)
  33. };
  34. };
  35. }
  36. function findKey(object, predicate) {
  37. for (var key in object) {
  38. if (object.hasOwnProperty(key) && predicate(object[key])) {
  39. return key;
  40. }
  41. }
  42. }
  43. function findIndex(array, predicate) {
  44. for (var key = 0; key < array.length; key++) {
  45. if (predicate(array[key])) {
  46. return key;
  47. }
  48. }
  49. }
  50. module.exports = exports.default;