MCPcopy Create free account
hub / github.com/microsoft/typescript-go / FromString

Function FromString

internal/jsnum/string.go:41–97  ·  view source on GitHub ↗

https://tc39.es/ecma262/2024/multipage/abstract-operations.html#sec-stringtonumber

(s string)

Source from the content-addressed store, hash-verified

39
40// https://tc39.es/ecma262/2024/multipage/abstract-operations.html#sec-stringtonumber
41func FromString(s string) Number {
42 // Implementing StringToNumber exactly as written in the spec involves
43 // writing a parser, along with the conversion of the parsed AST into the
44 // actual value.
45 //
46 // We've already implemented a number parser in the scanner, but we can't
47 // import it here. We also do not have the conversion implemented since we
48 // previously just wrote `+literal` and let the runtime handle it.
49 //
50 // The strategy below is to instead break the number apart and fix it up
51 // such that Go's own parsing functionality can handle it. This won't be
52 // the fastest method, but it saves us from writing the full parser and
53 // conversion logic.
54
55 s = strings.TrimFunc(s, isStrWhiteSpace)
56
57 switch s {
58 case "":
59 return 0
60 case "Infinity", "+Infinity":
61 return Inf(1)
62 case "-Infinity":
63 return Inf(-1)
64 }
65
66 for _, r := range s {
67 if !isNumberRune(r) {
68 return NaN()
69 }
70 }
71
72 if n, ok := tryParseInt(s); ok {
73 return n
74 }
75
76 // Cut this off first so we can ensure -0 is returned as -0.
77 s, negative := strings.CutPrefix(s, "-")
78
79 if !negative {
80 s, _ = strings.CutPrefix(s, "+")
81 }
82
83 if first, _ := utf8.DecodeRuneInString(s); !stringutil.IsDigit(first) && first != '.' {
84 return NaN()
85 }
86
87 f := parseFloatString(s)
88 if math.IsNaN(f) {
89 return NaN()
90 }
91
92 sign := 1.0
93 if negative {
94 sign = -1.0
95 }
96 return Number(math.Copysign(f, sign))
97}
98

Callers 15

newCaseClauseTrackerFunction · 0.92
classifyPropertyNameFunction · 0.92
isNumericLiteralNameFunction · 0.92
isValidNumberStringFunction · 0.92
checkExpressionWorkerMethod · 0.92
evaluateEntityMethod · 0.92
indexTypeLessThanFunction · 0.92

Calls 8

IsDigitFunction · 0.92
InfFunction · 0.85
isNumberRuneFunction · 0.85
NaNFunction · 0.85
tryParseIntFunction · 0.85
parseFloatStringFunction · 0.85
IsNaNMethod · 0.80
NumberTypeAlias · 0.70

Tested by 3

TestFromStringFunction · 0.56
TestStringRoundtripFunction · 0.56
FuzzFromStringJSFunction · 0.56