ap.js

  1. /**
  2. * Applies a list of functions to a list of values and returns a combined result array
  3. *
  4. * @function ap
  5. * @description Applies a list of functions to a list of values and returns a combined result array
  6. * @since v1.0.2
  7. * @sig @sig [a -> b] -> [a] -> [b]
  8. * @param {(Function[]|Function|Applicative)} fns - An array of functions or a function or an applicative
  9. * @param {Array} vals - An array of values
  10. * @return {Iterable} [a]
  11. **/
  12. import curry from './curry'
  13. import curry1 from './_private/curry1'
  14. import is from './is'
  15. import fold from './array/fold'
  16. import map from './array/map'
  17. const isFunction = is('Function')
  18. export default curry(function ap (fns, vals) {
  19. if (isFunction(fns.ap)) {
  20. return fns.ap(vals)
  21. }
  22. if (isFunction(fns)) {
  23. return x => fns(x)(vals(x))
  24. }
  25. return fold((acc, f) => acc.concat(map(curry1(f), vals)), [], fns)
  26. })