Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cond.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var apply = require('./_apply'),
  2. arrayMap = require('./_arrayMap'),
  3. baseIteratee = require('./_baseIteratee'),
  4. baseRest = require('./_baseRest');
  5. /** Error message constants. */
  6. var FUNC_ERROR_TEXT = 'Expected a function';
  7. /**
  8. * Creates a function that iterates over `pairs` and invokes the corresponding
  9. * function of the first predicate to return truthy. The predicate-function
  10. * pairs are invoked with the `this` binding and arguments of the created
  11. * function.
  12. *
  13. * @static
  14. * @memberOf _
  15. * @since 4.0.0
  16. * @category Util
  17. * @param {Array} pairs The predicate-function pairs.
  18. * @returns {Function} Returns the new composite function.
  19. * @example
  20. *
  21. * var func = _.cond([
  22. * [_.matches({ 'a': 1 }), _.constant('matches A')],
  23. * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
  24. * [_.stubTrue, _.constant('no match')]
  25. * ]);
  26. *
  27. * func({ 'a': 1, 'b': 2 });
  28. * // => 'matches A'
  29. *
  30. * func({ 'a': 0, 'b': 1 });
  31. * // => 'matches B'
  32. *
  33. * func({ 'a': '1', 'b': '2' });
  34. * // => 'no match'
  35. */
  36. function cond(pairs) {
  37. var length = pairs == null ? 0 : pairs.length,
  38. toIteratee = baseIteratee;
  39. pairs = !length ? [] : arrayMap(pairs, function(pair) {
  40. if (typeof pair[1] != 'function') {
  41. throw new TypeError(FUNC_ERROR_TEXT);
  42. }
  43. return [toIteratee(pair[0]), pair[1]];
  44. });
  45. return baseRest(function(args) {
  46. var index = -1;
  47. while (++index < length) {
  48. var pair = pairs[index];
  49. if (apply(pair[0], this, args)) {
  50. return apply(pair[1], this, args);
  51. }
  52. }
  53. });
  54. }
  55. module.exports = cond;