I want to improve my JS skills by doing challenges. My current challenge is: Write a script which allow user to enter number and then print all prime numbers from 0 to that number.
const PrimeFinder = (function() {
const PRIMES = [];
const MAX_RANGE = 10000;
// cache DOM
const EL_FIND = document.getElementById('find');
const EL_RESULT = document.getElementById('result');
const EL_SEARCH = document.getElementById('search');
// bind events
EL_FIND.addEventListener('click', findPrimes);
function _renderResult() {
for (let i = 0; i < PRIMES.length; i++) {
const EL_PRIME = EL_RESULT.appendChild(document.createElement('div'));
EL_PRIME.textContent = PRIMES[i];
}
}
function _resetResult() {
PRIMES.length = 0;
EL_RESULT.textContent = '';
}
function _validUserInput(N) {
return !isNaN(parseFloat(N)) &&
isFinite(N) &&
N >= 0 &&
N <= MAX_RANGE;
}
function isPrime(n) {
let start = 2;
while (start <= Math.sqrt(n)) {
if (n % start++ < 1) return false;
}
return n > 1;
}
function findPrimes(val) {
const USER_INPUT = (typeof val === 'number') ? val : EL_SEARCH.value;
_resetResult();
if (_validUserInput(USER_INPUT)) {
for (let i = 2; i <= USER_INPUT; i++) {
if (isPrime(i)) PRIMES.push(i);
}
_renderResult();
return PRIMES;
}
}
const publicAPI = {
isPrime: isPrime,
findPrimes: findPrimes
}
return publicAPI;
})();
body,
html {
padding: 0;
margin: 0;
}
.container {
max-width: 320px;
margin: 0 auto;
}
#search,
#find {
background: #fff;
color: #000;
height: 26px;
line-height: 26px;
margin: 0;
padding: 0;
box-sizing: border-box;
border: 1px solid #666;
}
#find {
width: 120px;
}
#search {
width: 190px;
}
#result {
margin: 10px 0;
}
#result>div {
width: 20%;
float: left;
box-sizing: border-box;
text-align: center;
color: #fff;
line-height: 48px;
background: coral;
border: 2px solid #fff;
}
#result div:hover {
background-color: red;
}
<div class="container">
<h1>Prime Number Finder</h1>
<input placeholder="" id="search" type="number">
<button id="find">Find</button>
<div id="result"></div>
</div>
I would like to know what could be done better and why.