0

I need to write function that returns 3strings after character ', ' so if there is none or 1 or 2 or 3 to return empty string if ', ' character is found else return 3 strings...i wrote these function but it is very cpu intensive...can be shorter and faster code?

https://jsfiddle.net/1nfyq327/

    var str = 'AAA BBB CC., DD EE, FF FF, GG GG, HH HH, II II, JJ JJ, GG GG';

    var res = str.substring(0, str.indexOf(', ', str.indexOf(', ', str.indexOf(', ')+1)+1));

    console.log(res);

Result is:

AAA BBB CC., DD EE, FF FF

Result is fine but i need faster code because it will execute on low power cpu so speed is very cruicial...

7
  • 1
    please add the wanted result as well. Commented Oct 23, 2019 at 9:59
  • wanted result updated... Commented Oct 23, 2019 at 10:01
  • u can split on ', ' and merge 3 item, but better soulotion for problem like this is regular expression Commented Oct 23, 2019 at 10:02
  • What makes you think it’s CPU intensive? Commented Oct 23, 2019 at 10:03
  • Can you post example code using regular expression? Commented Oct 23, 2019 at 10:06

3 Answers 3

1

Use split , slice and join:

var str = 'AAA BBB CC., DD EE, FF FF, GG GG, HH HH, II II, JJ JJ, GG GG';


var result = str.split(',').slice(0,3).join(',');

console.log(result);

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

Comments

1

In terms of speed there is not that much you can do.
The code you wrote runs in O(n), which is the best possible time complexity for your problem.

You can play around with native functions (split(), substring()... that are implemented in c++ and therefore will run quickly) to see if one of them is faster, or rewrite it in pure javascript with a for loop. And compare the results.

In your case the best thing you can really do is write a little benchmark testing how fast your solution is and compare that. Althought there is high chance that there is something else in your code that runs slowly. :)

Comments

1

You could split with a limit of String#split and join the array.

var string = 'AAA BBB CC., DD EE, FF FF, GG GG, HH HH, II II, JJ JJ, GG GG',
    result = string.split(',', 3).join(',')

console.log(result);

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.