OLD | NEW |
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file |
2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
5 part of dart.core; | 5 part of dart.core; |
6 | 6 |
7 /** | 7 /** |
8 * An integer or floating-point number. | 8 * An integer or floating-point number. |
9 * | 9 * |
10 * It is a compile-time error for any type other than [int] or [double] | 10 * It is a compile-time error for any type other than [int] or [double] |
(...skipping 421 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
432 * If no [onError] is supplied, it defaults to a function that throws a | 432 * If no [onError] is supplied, it defaults to a function that throws a |
433 * [FormatException]. | 433 * [FormatException]. |
434 * | 434 * |
435 * For any number `n`, this function satisfies | 435 * For any number `n`, this function satisfies |
436 * `identical(n, num.parse(n.toString()))` (except when `n` is a NaN `double` | 436 * `identical(n, num.parse(n.toString()))` (except when `n` is a NaN `double` |
437 * with a payload). | 437 * with a payload). |
438 */ | 438 */ |
439 static num parse(String input, [num onError(String input)]) { | 439 static num parse(String input, [num onError(String input)]) { |
440 String source = input.trim(); | 440 String source = input.trim(); |
441 // TODO(lrn): Optimize to detect format and result type in one check. | 441 // TODO(lrn): Optimize to detect format and result type in one check. |
442 _parseError = false; | 442 num result = int.parse(source, onError: _returnIntNull); |
443 num result = int.parse(source, onError: _onParseErrorInt); | 443 if (result != null) return result; |
444 if (!_parseError) return result; | 444 result = double.parse(source, _returnDoubleNull); |
445 _parseError = false; | 445 if (result != null) return result; |
446 result = double.parse(source, _onParseErrorDouble); | |
447 if (!_parseError) return result; | |
448 if (onError == null) throw new FormatException(input); | 446 if (onError == null) throw new FormatException(input); |
449 return onError(input); | 447 return onError(input); |
450 } | 448 } |
451 | 449 |
452 /** Helper functions for [parse]. */ | 450 /** Helper functions for [parse]. */ |
453 static bool _parseError = false; | 451 static int _returnIntNull(String _) => null; |
454 static int _onParseErrorInt(String _) { | 452 static double _returnDoubleNull(String _) => null; |
455 _parseError = true; | |
456 return 0; | |
457 } | |
458 static double _onParseErrorDouble(String _) { | |
459 _parseError = true; | |
460 return 0.0; | |
461 } | |
462 } | 453 } |
OLD | NEW |