parseInt.js 1.5 KB

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