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"));

3
  • do you have some inoputs and outputs? does the code work? Commented Sep 4, 2020 at 10:40
  • Not about making sense, more about being on topic. Please visit the help center, take the tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output using the [<>] snippet editor. Commented Sep 4, 2020 at 10:40
  • @NinaScholz Run the snippet Commented Sep 4, 2020 at 10:41

2 Answers 2

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"));

Sign up to request clarification or add additional context in comments.

2 Comments

Arrgh. Took me several minutes playing with exec to do this!
At least mine can see if it is an operator or not
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.