( expr: number | Expression | undefined )
| 137 | * Unlike `toInteger()` this functions fails if the expression is not an |
| 138 | * integer. `toInteger()` will round the value to the nearest integer. |
| 139 | */ |
| 140 | export function asSmallInteger( |
| 141 | expr: number | Expression | undefined |
| 142 | ): number | null { |
| 143 | if (expr === undefined || expr === null) return null; |
| 144 | if (typeof expr === 'number') { |
| 145 | if ( |
| 146 | Number.isInteger(expr) && |
| 147 | expr >= -SMALL_INTEGER && |
| 148 | expr <= SMALL_INTEGER |
| 149 | ) |
| 150 | return expr; |
| 151 | return null; |
| 152 | } |
| 153 | if (!isNumber(expr)) return null; |
| 154 | const num = expr.numericValue; |
| 155 | |
| 156 | if (typeof num === 'number') { |
| 157 | if (Number.isInteger(num) && num >= -SMALL_INTEGER && num <= SMALL_INTEGER) |
| 158 | return num; |
| 159 | return null; |
| 160 | } |
| 161 | |
| 162 | if (num.im !== 0) return null; |
| 163 | |
| 164 | const n = num.re; |
| 165 | if (Number.isInteger(n) && n >= -SMALL_INTEGER && n <= SMALL_INTEGER) |
| 166 | return Number(n); |
| 167 | return null; |
| 168 | } |
| 169 | |
| 170 | /** |
no test coverage detected