I wanted to practice functional programming (fp) without using any library but using vanilla JS only. So I took a problem from Project Euler:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
This is my solution:
(function () {
'use strict';
function* checkForPrime(n) {
let m = Math.floor(Math.sqrt(n) + 1);
while (true) {
if (n < 2) {
yield false;
return;
}
if (m < 2 || n === 2 || n === 3) {
yield true;
return;
}
if (n % m === 0) {
yield false;
return;
}
m--;
}
}
const isPrime = n => checkForPrime(n)
.next();
function* searchForPrimeNumbers(max) {
let primeCounter = 0;
let newPrimeNumber = 1;
let runningNumber = 1;
while (true) {
if (primeCounter === max) {
yield newPrimeNumber;
return newPrimeNumber;
}
if (isPrime(runningNumber)
.value) {
newPrimeNumber = runningNumber;
primeCounter = primeCounter + 1;
}
runningNumber++;
}
}
const finalsolution = searchForPrimeNumbers(1e4 + 1);
const findPrimeTill10001 = () => {
return finalsolution.next()
.value ? finalsolution.next()
.value : findPrimeTill10001();
};
const solution = findPrimeTill10001();
console.log(solution);
})();
As you can see, it is not consistent with the idea of FP. First I wanted to write it using recursion but I hit the stack limit. Therefore I used generators (and loops). That was the only solution I could come up with that resembles FP.
Any suggestions how to write in FP without any additional FP-Library (i.e. in pure JS only) is much appreciated.
yield newPrimeNumber;
andreturn newPrimeNumber;
? \$\endgroup\$