Provide a positive integer (0 < n
).
Returns an array of all factors of n
.
If there are no factors, returns an empty array.
Based on user boo1ean's solution here: https://www.codewars.com/kata/reviews/55aa0d71c1eba8a65a000132/groups/5787db6eba5c4b1c8c0016ae
function getFactors (n) {
if (n < 1 || ! Number.isInteger(n)) return [];
let divisors = [];
// Only iterates up to n/2, since no divisor will be greater than that
for (let i = 1; i <= n / 2; ++i) {
if (n % i) continue;
else divisors.push(i);
}
// Push the original number n to array
return divisors.concat([n]);
}
describe("Solution", function(){
it("sBasic tests", function(){
Test.assertSimilar(getFactors(0), [], "Should return empty array");
Test.assertSimilar(getFactors('string'), [], "Is not a number so should return an empty array");
Test.assertSimilar(getFactors(1), [1], "'1' should be the only divisor of '1'");
Test.assertSimilar(getFactors(13), [1, 13], "'13' is a prime number, so '1, 13' should be its divisors");
Test.assertSimilar(getFactors(50), [1, 2, 5, 10, 25, 50]);
});
});