parseInt.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var root = require('./_root'),
  2. toString = require('./toString');
  3. /** Used to match leading whitespace. */
  4. var reTrimStart = /^\s+/;
  5. /* Built-in method references for those with the same name as other `lodash` methods. */
  6. var nativeParseInt = root.parseInt;
  7. /**
  8. * Converts `string` to an integer of the specified radix. If `radix` is
  9. * `undefined` or `0`, a `radix` of `10` is used unless `value` is a
  10. * hexadecimal, in which case a `radix` of `16` is used.
  11. *
  12. * **Note:** This method aligns with the
  13. * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
  14. *
  15. * @static
  16. * @memberOf _
  17. * @since 1.1.0
  18. * @category String
  19. * @param {string} string The string to convert.
  20. * @param {number} [radix=10] The radix to interpret `value` by.
  21. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  22. * @returns {number} Returns the converted integer.
  23. * @example
  24. *
  25. * _.parseInt('08');
  26. * // => 8
  27. *
  28. * _.map(['6', '08', '10'], _.parseInt);
  29. * // => [6, 8, 10]
  30. */
  31. function parseInt(string, radix, guard) {
  32. if (guard || radix == null) {
  33. radix = 0;
  34. } else if (radix) {
  35. radix = +radix;
  36. }
  37. return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
  38. }
  39. module.exports = parseInt;