Porting NREL's Solar Position Algorithm from C to TypeScript
The NREL SPA is a 4,000-line C program that calculates solar position to 0.0003 degree accuracy. I ported it to TypeScript and kept the precision.
The Solar Position Algorithm published by the National Renewable Energy Laboratory calculates the sun's position (zenith angle, azimuth, declination, elevation) for any point on Earth at any time between the years -2000 and 6000. The reference implementation is a 4,000-line C program. I wanted it in JavaScript.
The first version, solar-spa, was a line-by-line C port I pushed to GitHub in April 2023. It worked but was not idiomatic JavaScript. Six months later I rewrote it as nrel-spa: a clean TypeScript module with proper exports, tree-shaking support, and test coverage against the NREL reference values.
The hardest part was not the math. The algorithm uses Julian dates, Delaunay parameters, and periodic terms for nutation and obliquity. All of that translates directly from C to TypeScript. The hard part was precision. JavaScript uses 64-bit IEEE 754 floats, same as C double. But the order of floating-point operations matters, and some C compilers reorder operations in ways that change the last few bits. Matching the reference output to 0.0003 degrees required careful attention to operation order.
nrel-spa is now used in prayer time calculators (pray-calc), astronomical tools (moon-cycle), and solar energy projects. Having the algorithm in TypeScript means it runs in the browser, on the server, and in React Native apps without any native bindings.