let f, c, d, g, i; /** * Note: this will pollute global scope. * Accepts a floating point number and returns a fractional representation of `n` * in the form `[numerator, denominator]`. * If you encounter a stack overflow, try increasing the value of `e`, * i.e. do not set `e` to `Number.EPSILON`. * @param {number} n a floating point number * @param {number?} e epsilon * @returns {[number, number]} a fractional representation of `n` */ f = (n, e = 1e-3) => ( c = ( g = (n, e, c = []) => // `g` is a lambda that builds a continued fractional // representation of an `n`: (d = n - (i = ~~n)) > e // if the fractional component of the number passed to `g` // is greater than the epsilon ? [...c, i, ...g(1 / d, e, c)] // ...append the natural component of `n`, and the result // of recursively calling `g` on the inverse of the // fractional component (e.g. // `g(3.5, e, [1]) == g(1 / 0.5, e, [1, 3])`) : [...c, i] // ...else append `n` and return the generated continued // fraction. )(n, e).reverse() // call `g` with our initial arguments and reverse // the result. ).reduce( // then, reduce our RTL continued fraction into a standard // fractional form of `n`: ([d, n], a) => [a * d + n, d], // by recursively reducing `1 / [a + n / d]` into the // equivalent `d / [a * d + n]` (e.g. // 1 / [2 + 3 / 4] == 4 / [2 * 4 + 3] == 4 / 11) [c.shift(), 1] // starting with the smallest component of the // continued fraction and working outwards ) // leaving us with a fractional representation of `n`.