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