parseInt.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. var isIterateeCall = require('../internal/isIterateeCall'),
  2. trim = require('./trim');
  3. /** Used to detect hexadecimal string values. */
  4. var reHasHexPrefix = /^0[xX]/;
  5. /* Native method references for those with the same name as other `lodash` methods. */
  6. var nativeParseInt = global.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 hexadecimal,
  10. * in which case a `radix` of `16` is used.
  11. *
  12. * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
  13. * of `parseInt`.
  14. *
  15. * @static
  16. * @memberOf _
  17. * @category String
  18. * @param {string} string The string to convert.
  19. * @param {number} [radix] The radix to interpret `value` by.
  20. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
  21. * @returns {number} Returns the converted integer.
  22. * @example
  23. *
  24. * _.parseInt('08');
  25. * // => 8
  26. *
  27. * _.map(['6', '08', '10'], _.parseInt);
  28. * // => [6, 8, 10]
  29. */
  30. function parseInt(string, radix, guard) {
  31. // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
  32. // Chrome fails to trim leading <BOM> whitespace characters.
  33. // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
  34. if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
  35. radix = 0;
  36. } else if (radix) {
  37. radix = +radix;
  38. }
  39. string = trim(string);
  40. return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
  41. }
  42. module.exports = parseInt;