Reputation: 477
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...
Upvotes: 0
Views: 76
Reputation: 386560
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);
Upvotes: 1
Reputation: 14389
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);
Upvotes: 1
Reputation: 2166
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. :)
Upvotes: 1