1

This is one of my function for a calculator project. First I needed to convert the input string into an array, and do the operation later. (assuming that input has only numbers and '+' sign for now.

My question here is, how do I improve this code? What are the other ways to deal with this problem? (Time complexity, cleanness, shorter code.......whatever)

function convertArray(input) {
  let array = [];
  let num = "";
  for (let i = 0; i < input.length; i++) {
    if (input.charAt(i) == '+') {
      array.push(input.charAt(i));
    } else {
      do {
        num += input.charAt(i);
        i++;
      } while (i < input.length && input.charAt(i) !== '+');
      array.push(num);
      num = "";
      i--;
    }
  }
  return array;
}

console.log(convertArray("10+2+3000+70+1"));
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Xiang
  • 13
  • 3
  • do you have some inoputs and outputs? does the code work? – Nina Scholz Sep 04 '20 at 10:40
  • Not about making sense, more about being on topic. Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan Sep 04 '20 at 10:40
  • @NinaScholz Run the snippet – mplungjan Sep 04 '20 at 10:41

3 Answers3

2

You could split with a group. this add the group as well to the array.

For other calculation signs, you could add them to the brackets.

const convertArray = string => string.split(/([+])/);

console.log(convertArray("10+2+3000+70+1"));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

const q = prompt('Sum?');
alert('Answer: ' + eval(q));

Would not recommend using eval, but if all you need is a quick and dirty trick, it works. Personally, I'd recommend a library such as Math.js, but any will do.

If you really need to do this by yourself for a project, I'd recommend checking out the answers here: Evaluating a string as a mathematical expression in JavaScript.

Hope you succeed in whatever you're planning on doing.

PiggyPlex
  • 631
  • 1
  • 4
  • 15
0

It seems the complexity must have something to do with your wish to determing operators. In your code you just push them all into the array. To do that is like

const re = /((\d+)|([^\d]+))/g
const convertArray = str => {
  let match, arr=[];
  while (match = re.exec(str)) {
    arr.push(match[1]) // here you can determine if you have an operator
    console.log(match[1],"Operator?",!/^\d+$/.test(match[1]))
  }
  return arr
}
const str = "10+2+3000+70+1";

console.log(convertArray(str));
mplungjan
  • 169,008
  • 28
  • 173
  • 236