from-function.js 950 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import fromPrimative from './from-primative';
  2. /**
  3. * Check if the value from a function matches some condition
  4. *
  5. * Each key on the matcher object is passed to getValue, the returned value must match
  6. * with the value of that matcher
  7. *
  8. * Example:
  9. * ```js
  10. * matches.fromFunction(
  11. * (attr => node.getAttribute(attr),
  12. * {
  13. * 'aria-hidden': /^true|false$/i
  14. * }
  15. * )
  16. * ```
  17. *
  18. * @private
  19. * @param {Function} getValue
  20. * @param {Object} matcher matcher
  21. * @returns {Boolean}
  22. */
  23. function fromFunction(getValue, matcher) {
  24. const matcherType = typeof matcher;
  25. if (
  26. matcherType !== 'object' ||
  27. Array.isArray(matcher) ||
  28. matcher instanceof RegExp
  29. ) {
  30. throw new Error('Expect matcher to be an object');
  31. }
  32. // Check that the property has all the expected values
  33. return Object.keys(matcher).every(propName => {
  34. return fromPrimative(getValue(propName), matcher[propName]);
  35. });
  36. }
  37. export default fromFunction;