Use Array.from()

Updated the code to utilize `Array.from()` to check for factors, this can be shortened even further (follow-up commits)
This commit is contained in:
Angelos Chalaris
2018-01-03 14:49:34 +02:00
committed by GitHub
parent 07809ddc90
commit 093b806e7d

View File

@ -18,21 +18,18 @@ const factors = (int,prime = false,powers = false) => {
} }
const isPrime = num => { const isPrime = num => {
const boundary = Math.floor(Math.sqrt(num)); const boundary = Math.floor(Math.sqrt(num));
for (var i = 2; i <= boundary; i++) if (num % i == 0) return false; for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
return num >= 2 return num >= 2
} }
let array = [] let isNeg = int < 0;
const posFactor = num => { int = isNeg ? -int : int;
let arr = [] let array = Array.from({length: int - 1}).map((val,i) => int % (i+2) === 0 ? (i+2) : false).filter(val => val);
for (let i = 2; i <= num; i++) if (num % i === 0) arr.push(i) if(isNeg) array = array.reduce((acc,val) => {acc.push(val); acc.push(-val); return acc}, []);
return arr
}
if (int >= 0) array = posFactor(int)
else {posFactor(-int).forEach(el => array.push(el,-el))}
array = prime ? array.filter(el => isPrime(el)) : array; array = prime ? array.filter(el => isPrime(el)) : array;
return powers ? array.map(x => [x,howManyTimes(int,x)]) : array return powers ? array.map(x => [x,howManyTimes(int,x)]) : array
}; }
``` ```
```js ```js
factors(12); //[2,3,4,6,12] factors(12); //[2,3,4,6,12]
factors(12,true); //[2,3] factors(12,true); //[2,3]