@toreda/strong-types
Version:
Better TypeScript code in fewer lines.
1 lines • 2.85 kB
Source Map (JSON)
{"version":3,"sources":["../src/to/int/number.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,GAAG,MAAM,QAAQ,CAAC;AAGzB;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,GAAG,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CA2C/E","file":"number.d.ts","sourcesContent":["/**\n *\tMIT License\n *\n *\tCopyright (c) 2019 - 2021 Toreda, Inc.\n *\n *\tPermission is hereby granted, free of charge, to any person obtaining a copy\n *\tof this software and associated documentation files (the \"Software\"), to deal\n *\tin the Software without restriction, including without limitation the rights\n *\tto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n *\tcopies of the Software, and to permit persons to whom the Software is\n *\tfurnished to do so, subject to the following conditions:\n\n * \tThe above copyright notice and this permission notice shall be included in all\n * \tcopies or substantial portions of the Software.\n *\n * \tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n *\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n *\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * \tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n *\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n *\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * \tSOFTWARE.\n *\n */\nimport Big from 'big.js';\nimport {typeMatch} from '../../type/match';\n\n/**\n * Convert from common numeric types to JavaScript `number` type.\n * @param value\n * @returns\n *\n * @category Strong Helpers\n */\nexport function toIntNumber(value?: number | string | Big | null): number | null {\n\tif (value === undefined || value === null) {\n\t\treturn null;\n\t}\n\n\tlet result: number | null;\n\n\t// Converting Big -> number is generally as precision may be lost.\n\t// Support for Big values is provided for ease of use in cases where\n\t// the caller would have to convert input before calling.\n\tif (typeMatch(value, Big)) {\n\t\t// Throws when Big value will not fit in number.\n\t\ttry {\n\t\t\tresult = value.toNumber();\n\t\t} catch (e) {\n\t\t\tresult = null;\n\t\t}\n\t} else if (typeof value === 'string') {\n\t\tresult = parseFloat(value);\n\t} else if (typeof value === 'number') {\n\t\tresult = value;\n\t} else {\n\t\tresult = null;\n\t}\n\n\tif (result === null || isNaN(result)) {\n\t\treturn null;\n\t}\n\n\tif (result >= Number.POSITIVE_INFINITY || result <= Number.NEGATIVE_INFINITY) {\n\t\treturn null;\n\t}\n\n\tif (result < Number.MIN_SAFE_INTEGER || result > Number.MAX_SAFE_INTEGER) {\n\t\treturn null;\n\t}\n\n\t// Reject values with decimals.\n\tif (Math.floor(result) !== result) {\n\t\treturn null;\n\t}\n\n\treturn result;\n}\n"]}