Parcourir la source

handle more edge cases in getNumberType

Alexander Rose il y a 5 ans
Parent
commit
a011600766

+ 7 - 0
src/mol-io/reader/_spec/common.spec.ts

@@ -21,5 +21,12 @@ describe('common', () => {
         expect(getNumberType('0.42')).toBe(NumberType.Float)
         expect(getNumberType('Foo123')).toBe(NumberType.NaN)
         expect(getNumberType('11.0829(23)')).toBe(NumberType.NaN)
+        expect(getNumberType('1..2')).toBe(NumberType.NaN)
+        expect(getNumberType('.')).toBe(NumberType.NaN)
+        expect(getNumberType('-.')).toBe(NumberType.NaN)
+        expect(getNumberType('e')).toBe(NumberType.NaN)
+        expect(getNumberType('-e')).toBe(NumberType.NaN)
+        expect(getNumberType('1e')).toBe(NumberType.Scientific)
+        expect(getNumberType('-1e')).toBe(NumberType.Scientific)
     });
 });

+ 10 - 1
src/mol-io/reader/common/text/number-parser.ts

@@ -103,10 +103,16 @@ function getNumberTypeScientific(str: string, start: number, end: number) {
 /** The whole range must match, otherwise returns NaN */
 export function getNumberType(str: string): NumberType {
     let start = 0, end = str.length;
-    if (str.charCodeAt(start) === 45) {
+
+    if (str.charCodeAt(start) === 45) { // -
         ++start;
     }
 
+    // string is . or -.
+    if (str.charCodeAt(start) === 46 && end - start === 1) {
+        return NumberType.NaN
+    }
+
     while (start < end) {
         let c = str.charCodeAt(start) - 48;
         if (c >= 0 && c < 10) {
@@ -127,6 +133,9 @@ export function getNumberType(str: string): NumberType {
             }
             return hasDigit ? NumberType.Float : NumberType.Int;
         } else if (c === 53 || c === 21) { // 'e'/'E'
+            if (start === 0 || start === 1 && str.charCodeAt(0) === 45) {
+                return NumberType.NaN; // string starts with e/E or -e/-E
+            }
             return getNumberTypeScientific(str, start + 1, end);
         }
         else break;