Hello guys,
I have just created this humble little algorithm for one of the JS projects.
Could you kindly let me know about my probable big chunk of flaws, advice or observations?
Thanks in advance =D
I am here considering this data structure, consisting in an Array of Objects(I preferred it over creating it and wasting more lines of code) which in my opinion is more readable and closer to real-life basic precautions for better readability and reliability.
This recursive function is a reducer, consisting of the following logic:
=> Gets the input number and checks for the closest(biggest) number available.
=> Finds the corresponding number´s numeral (item id) and pushes it into an array.
=> Subtracts the numeral found from the input value and checks for a reminder
=> In case there is a reminder left (input value - numeral found) run the function again
=> When the reminder is 0, join the array and return the function´s value
const alg = (numb, arr) => {
      const romanNumbers = [
        { id: "I", val: 1 },
        { id: "IV", val: 4 },
        { id: "V", val: 5 },
        { id: "IX", val: 9 },
        { id: "X", val: 10 },
        { id: "XL", val: 40 },
        { id: "L", val: 50 },
        { id: "XC", val: 90 },
        { id: "C", val: 100 },
        { id: "CD", val: 400 },
        { id: "D", val: 500 },
        { id: "CM", val: 900 },
        { id: "M", val: 1000 }
      ];
      const reducer = numb =>
        romanNumbers
        .reduce((a, b) => ({ val: b.val > numb ? a.val : b.val }));
      arr.push(...romanNumbers
        .filter(v => v.val === reducer(numb).val)
        .map(v => v.id));
      const res = numb - reducer(numb).val;
      return res > 0 ? alg(res, arr) : arr.join("");
    };
  
  const convertToRoman = num => alg(num, [])
  
  convertToRoman(36);