numberSelector.js
1 export class NumberSelector { 2 constructor(uiService) { 3 this.uiService = uiService; 4 } 5 6 show = async (currentValue, promptMessage, allowMetricPostfixes) => { 7 try { 8 var valueStr = await this.promptForValueStr(promptMessage); 9 valueStr = valueStr.replaceAll(" ", ""); 10 const mult = this.getMetricsMult(valueStr, allowMetricPostfixes); 11 const value = this.getNumericValue(valueStr); 12 return value * mult; 13 } catch { 14 return currentValue; 15 } 16 }; 17 18 getMetricsMult = (valueStr, allowMetricPostfixes) => { 19 if (!allowMetricPostfixes) return 1; 20 const lower = valueStr.toLowerCase(); 21 if (lower.endsWith("tb") || lower.endsWith("t")) return Math.pow(1024, 4); 22 if (lower.endsWith("gb") || lower.endsWith("g")) return Math.pow(1024, 3); 23 if (lower.endsWith("mb") || lower.endsWith("m")) return Math.pow(1024, 2); 24 if (lower.endsWith("kb") || lower.endsWith("k")) return Math.pow(1024, 1); 25 return 1; 26 }; 27 28 getNumericValue = (valueStr) => { 29 try { 30 const num = valueStr.match(/\d+/g); 31 const result = parseInt(num); 32 if (isNaN(result) || !isFinite(result)) { 33 throw new Error("Invalid input received."); 34 } 35 return result; 36 } catch (error) { 37 console.log("Failed to parse input: " + error.message); 38 throw error; 39 } 40 }; 41 42 promptForValueStr = async (promptMessage) => { 43 return this.uiService.askPrompt(promptMessage); 44 }; 45 }