Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active July 24, 2021 08:58
Show Gist options
  • Save lewdev/e1a477b077c899c07e5f234b72ab0f88 to your computer and use it in GitHub Desktop.
Save lewdev/e1a477b077c899c07e5f234b72ab0f88 to your computer and use it in GitHub Desktop.
Given a number, this method returns an ordered array of its factors.
const getFactors = num => {
const maxFactorNum = Math.floor(Math.sqrt(num));
const factorArr = [];
let count = 0; // count of factors found < maxFactorNum
for (let i = 1; i <= maxFactorNum; i++) {
//inserting new elements in the middle using splice
if (num % i === 0) {
//(index, how many to remove, inserted element)
factorArr.splice(count, 0, i);
const otherFactor = num / i;
if (i !== otherFactor) {
//insert these factors in the front of the array
factorArr.splice(-count, 0, otherFactor);
}
count++;
}
}
//swapping first and last elements
const lastIndex = factorArr.length - 1;
const temp = factorArr[lastIndex];
factorArr[lastIndex] = factorArr[0];
factorArr[0] = temp;
return factorArr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment