from-primative.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * Check if some value matches
  3. *
  4. * ```js
  5. * match.fromPrimative('foo', 'foo') // true, string is the same
  6. * match.fromPrimative('foo', ['foo', 'bar']) // true, string is included
  7. * match.fromPrimative('foo', /foo/) // true, string matches regex
  8. * match.fromPrimative('foo', str => str.toUpperCase() === 'FOO') // true, function return is truthy
  9. * match.fromPrimative('foo', '/foo/') // true, string matches regex string
  10. * ```
  11. *
  12. * @private
  13. * @param {String|Boolean|Array|Number|Null|Undefined} someString
  14. * @param {String|RegExp|Function|Array<String>|Null|Undefined} matcher
  15. * @returns {Boolean}
  16. */
  17. function fromPrimative(someString, matcher) {
  18. const matcherType = typeof matcher;
  19. if (Array.isArray(matcher) && typeof someString !== 'undefined') {
  20. return matcher.includes(someString);
  21. }
  22. if (matcherType === 'function') {
  23. return !!matcher(someString);
  24. }
  25. // RegExp.test(str) typecasts the str to a String value so doing
  26. // `/.*/.test(null)` returns true as null is cast to "null"
  27. if (someString !== null && someString !== undefined) {
  28. if (matcher instanceof RegExp) {
  29. return matcher.test(someString);
  30. }
  31. // matcher starts and ends with "/"
  32. if (/^\/.*\/$/.test(matcher)) {
  33. const pattern = matcher.substring(1, matcher.length - 1);
  34. return new RegExp(pattern).test(someString);
  35. }
  36. }
  37. return matcher === someString;
  38. }
  39. export default fromPrimative;