take.js 851 B

12345678910111213141516171819202122232425262728293031323334353637
  1. var baseSlice = require('./_baseSlice'),
  2. toInteger = require('./toInteger');
  3. /**
  4. * Creates a slice of `array` with `n` elements taken from the beginning.
  5. *
  6. * @static
  7. * @memberOf _
  8. * @since 0.1.0
  9. * @category Array
  10. * @param {Array} array The array to query.
  11. * @param {number} [n=1] The number of elements to take.
  12. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  13. * @returns {Array} Returns the slice of `array`.
  14. * @example
  15. *
  16. * _.take([1, 2, 3]);
  17. * // => [1]
  18. *
  19. * _.take([1, 2, 3], 2);
  20. * // => [1, 2]
  21. *
  22. * _.take([1, 2, 3], 5);
  23. * // => [1, 2, 3]
  24. *
  25. * _.take([1, 2, 3], 0);
  26. * // => []
  27. */
  28. function take(array, n, guard) {
  29. if (!(array && array.length)) {
  30. return [];
  31. }
  32. n = (guard || n === undefined) ? 1 : toInteger(n);
  33. return baseSlice(array, 0, n < 0 ? 0 : n);
  34. }
  35. module.exports = take;