Last active
September 13, 2018 00:36
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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