C's math.frexp in TypeScript
How to use
Install via yarn add locutus and import:
import { frexp } from 'locutus/c/math/frexp'.
Or with CommonJS: const { frexp } = require('locutus/c/math/frexp')
Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.
Examples
These examples are extracted from test cases that automatically verify our functions against their native counterparts.
| # | code | expected result |
|---|---|---|
| 1 | frexp(1) | [0.5, 1] |
| 2 | frexp(1.5) | [0.75, 1] |
| 3 | frexp(3 * Math.pow(2, 500)) | [0.75, 502] |
| 4 | frexp(-4) | [-0.5, 3] |
| 5 | frexp(Number.MAX_VALUE) | [0.9999999999999999, 1024] |
| 6 | frexp(Number.MIN_VALUE) | [0.5, -1073] |
| 7 | frexp(-Infinity) | [-Infinity, 0] |
| 8 | frexp(-0) | [-0, 0] |
| 9 | frexp(NaN) | [NaN, 0] |
C types and TypeScript/JavaScript
C is statically typed while TypeScript/JavaScript is dynamically typed. Locutus C functions accept TypeScript/JavaScript's flexible types but are only parity-verified for inputs that would be valid in C.
For example, abs() in TypeScript/JavaScript accepts floats (like C's fabs())
and handles strings gracefully, but only integer inputs are verified against native C.
This pragmatic approach gives you the expected C behavior for valid inputs while
leveraging TypeScript/JavaScript's flexibility for edge cases.
Notes
Instead of double frexp( double arg, int* exp ); this is built as [double, int] frexp( double arg ); due to the lack of pointers in JavaScript. See code comments for further information.
Here's what our current TypeScript equivalent to C's frexp found in the math.h header file looks like.
export function frexp(arg: number): [number, number] { |
Improve this function
Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.
View on GitHub · Edit on GitHub · View Raw
We have 20 C functions so far - help us add more
Got a rainy Sunday afternoon and a taste for a porting puzzle?
- Get inspiration from the C math.h documentation, the C math.h source.
- Click "New file" in the appropriate folder on GitHub. This will fork the project to your account, directly add the file to it, and send a Pull Request to us.
We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.
Star