Last active
February 8, 2018 15:24
-
-
Save krazov/100e495a1f83b6345b2a131dee1d5143 to your computer and use it in GitHub Desktop.
Some fun with `setImmediate`
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
function fibonacciProcessed(x) { | |
return new Promise(resolve => { | |
const calculation = function (resolveFn, n = 0, a = 0, b = 1) { | |
if (n > 1) { | |
setImmediate(() => { | |
calculation(resolveFn, n - 1, b, a + b); | |
}); | |
} | |
// else | |
resolveFn(b); | |
}; | |
calculation(resolve, x); | |
}); | |
} | |
fibonacciProcessed(1476).then(number => { | |
console.log(number); | |
}); | |
// counter concepts | |
// anti-example, will be slower and slower, eventually reaching vaporwave sampling level | |
// function fibonacci(x) { | |
// return x <= 1 ? x : fibonacci(x - 1) + fibonacci(x - 2); | |
// } | |
// | |
// console.log(fibonacci(process.argv[2])); | |
// as above, just with normal returns -- works just the same | |
// function fib(a, b, n) { | |
// if (n) { | |
// return fib(b, a + b, n - 1); | |
// } | |
// | |
// return a; | |
// } | |
// console.log(fib(0, 1, 1476)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment