helpers.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. export const addNumbersToGrid = (numbersArr, sign) => {
  2. const nrGrid = []
  3. for (let noIdx in numbersArr){
  4. let nr = numbersArr[noIdx].join("").replace(/ /g, " ");
  5. if (parseInt(noIdx) === numbersArr.length-1){
  6. nr = sign + " " + nr;
  7. }
  8. nrGrid.push({id: parseInt(noIdx)+3, number: nr});
  9. }
  10. return nrGrid;
  11. }
  12. const afterCommaLen = (number) => {
  13. let noStrList = number.toString().split(".");
  14. if (noStrList.length > 1){
  15. return noStrList[1].length
  16. }
  17. return 0
  18. }
  19. export function numbersToArrOfArr(numbers) {
  20. let befComma = Math.max(...numbers).toString().split(".")[0].length;
  21. let afterComma = Math.max(...numbers.map(x => afterCommaLen(x)));
  22. let withComma = Math.max(...numbers.map(x => x.toString().indexOf(".")));
  23. let arrLength;
  24. if(withComma < 0){ // no comma found
  25. arrLength = befComma;
  26. }else{
  27. arrLength = befComma + afterComma + 1; // add comma and after comma len
  28. }
  29. let numbersArr = numbers.map(x => x.toString().split(""));
  30. for (let numArr of numbersArr){
  31. let commaIdx = numArr.indexOf(".");
  32. // without comma, add before
  33. while(commaIdx===-1 && numArr.length < befComma){
  34. numArr.unshift("&nbsp;"); // add " " before comma
  35. }
  36. // without comma, add after
  37. while(commaIdx===-1 && numArr.length < arrLength){
  38. numArr.push("&nbsp;"); // add " " after comma
  39. }
  40. // with comma, add before
  41. while(commaIdx>-1 && commaIdx!==befComma){
  42. numArr.unshift("&nbsp;"); // add " " before comma
  43. commaIdx = numArr.indexOf(".");
  44. }
  45. // with comma, add after
  46. while(numArr.length < arrLength){
  47. numArr.push("&nbsp;"); // add " " after comma
  48. }
  49. numArr.unshift("&nbsp;"); // for carry
  50. }
  51. return [numbersArr, befComma+1];
  52. // TODO: assert all have same length and comma at same index?
  53. }