Pages

peut on éviter switch case ?

function decomposition_nombres_premiers(n=1) {
 
  if (n==1) return [1];
  let p = [];
  for (let i = 2; i <= n; i++){
    while (n % i === 0){
      p.push(i);
      n /= i;
    }
  }
 
  let countedFactor = p.reduce(function (allPremiers, premier) {
      if (premier in allPremiers) {
  allPremiers[premier]++;
  }
  else {
    allPremiers[premier] = 1;
  }
  return allPremiers;
  }, {});
 
 
 
  return {p,countedFactor};
};

let nb = 1028;
let {p,countedFactor} = decomposition_nombres_premiers(nb);

console.log(p,countedFactor);

let result=`${nb} = `;
for (var [cle, valeur] of Object.entries(countedFactor)){
  switch (valeur) {
  case 1:
    result+=` ${cle} x`;
    break;
  case 2:
    result+=` ${cle}\u00B2 x`;
    break;
  case 3:
    result+=` ${cle}\u00B3 x`; 
    break;
  case 4:
    result+=` ${cle}\u2074 x`;
    break;
  case 5:
    result+=` ${cle}\u2075 x`;
    break;
  case 6:
    result+=` ${cle}\u2076 x`;
    break;
  case 7:
    result+=` ${cle}\u2077 x`;
    break;
  case 8:
    result+=` ${cle}\u2078 x`;
    break;
  case 9:
    result+=` ${cle}\u2079 x`;
    break;
  default:
    result+=` ${cle}(${valeur}) x`;
  }
  }
 
  console.log(result= result.substring(0, result.length - 1))