toLength.js 868 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. var baseClamp = require('./_baseClamp'),
  2. toInteger = require('./toInteger');
  3. /** Used as references for the maximum length and index of an array. */
  4. var MAX_ARRAY_LENGTH = 4294967295;
  5. /**
  6. * Converts `value` to an integer suitable for use as the length of an
  7. * array-like object.
  8. *
  9. * **Note:** This method is based on
  10. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  11. *
  12. * @static
  13. * @memberOf _
  14. * @since 4.0.0
  15. * @category Lang
  16. * @param {*} value The value to convert.
  17. * @returns {number} Returns the converted integer.
  18. * @example
  19. *
  20. * _.toLength(3.2);
  21. * // => 3
  22. *
  23. * _.toLength(Number.MIN_VALUE);
  24. * // => 0
  25. *
  26. * _.toLength(Infinity);
  27. * // => 4294967295
  28. *
  29. * _.toLength('3.2');
  30. * // => 3
  31. */
  32. function toLength(value) {
  33. return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
  34. }
  35. module.exports = toLength;