Skip to content

Instantly share code, notes, and snippets.

@maxbisesi
Created January 2, 2024 01:41
Show Gist options
  • Save maxbisesi/8992db820e18edc2ade46dc38edee990 to your computer and use it in GitHub Desktop.
Save maxbisesi/8992db820e18edc2ade46dc38edee990 to your computer and use it in GitHub Desktop.
Prime Factorization with flatMap
// ======================
// Prime factorization with flatMap
//======================
// flatMap can be used as a way to add and remove items (modify the number of items) during a map.
// In other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one.
// it works like the opposite of filter.
var numbersTofactor = [20,1,17,2,3,15,16,100,157];
var factors = numbersTofactor.flatMap((n) => {
var allFactors = [];
const m = factor(allFactors,n); // [], 20
return [m];
});
function factor(allFactors,num) {
let nextGCF = findGCF(num); // 5
if(nextGCF !== 0) {
allFactors.push(nextGCF);
if(nextGCF == num) return allFactors;
let x = num / nextGCF; // x = 4
return factor(allFactors,x);
} else {
// cant be factored give up and return num and 1
return num == 1 ? [num] : [1,num];
}
}
function findGCF(num) {
const primes = [2,3,5,7];
if(primes.includes(num)) return num;
let smallest = 0;
let gcf = 0;
primes.forEach((p) => {
// can be factored
if(num % p == 0) {
// find smallest factor
if((num / p) < smallest || smallest == 0) {
smallest = num / p;
gcf = p;
}
}
});
return gcf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment