Skip to content

Instantly share code, notes, and snippets.

@jpidelatorre
Last active September 13, 2018 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpidelatorre/5f21b696a264e2a9f20fd32856efc43b to your computer and use it in GitHub Desktop.
Save jpidelatorre/5f21b696a264e2a9f20fd32856efc43b to your computer and use it in GitHub Desktop.
Returns an equivalent fraction to a number larger than 0 (limited by a rather limited call stack size cap)
f = ( // Given
n, // A number greater than 0 (limited by the call stack size cap)
a, // An optional numerator
b // And an optional denominator
) =>
[ // Have a collection of functions that
_ => f(n, a + 1, b), // - Adds one to the numerator if the fraction is smaller than the number
_ => `${a}/${b}`, // - Returns a string of the resulting fraction if it's equal to the number
_ => f(n, a, b + 1), // - Adds one to the denominator if the fraction is larger than the number
][ // And return the value of one based on
Math.sign( // The sign of the operation resulting from having
(a = a || 1) // The numerator, or 1 if none
/ // Divided by
(b = b || 1) // The denominator, or 1 if none
- n // Minus the number we are looking for
) + 1 // Aligned to the index of the needed function
](console.log(`${a}/${b}`)) // Also, print every step
f=(n,a,b)=>[_=>f(n,a+1,b),_=>`${a}/${b}`,_=>f(n,a,b+1),][Math.sign((a=a||1)/(b=b||1)-n)+1]()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment