0

I am receiving a tokenized string from the server in the form of status---delimiter---status where I may have up to 1000 statuses. There are only 6 different possible values for status. I am trying to find a way to search for all 6 at once and that gives me a count of each. I've come up with several less optimum ways of solving the issue but the best I could think of still effectively makes 2 full passes on the string and involves several substeps. I looked at regX .match and capture groups but couldn't seem to find any way to make that work better then one status at a time. I realize the performance difference wont be noticeable but now I just want to know, since in theory this should be doable (though maybe not with JavaScripts regX).

Example Set of statuses: [red,blue,green,orange,purple,pink] Delimiter (I can chose this): | String: red|purple|green|red|blue|orange|purple|blue

Result: [red: 2, blue: 2, green: 1, orange: 1, purple, 2, pink 0]

6
  • 1
    why not use var arr= your_string.split(delimiter) and then go through the array and count them? Commented Mar 28, 2014 at 19:36
  • That's my 2 pass solution. Since splitting is one full pass and then the array has to be searched through to place each status in the correct count. Commented Mar 28, 2014 at 19:38
  • could you tell your status options and the delimiter? Commented Mar 28, 2014 at 19:40
  • Added an example, the delimiter is my choice of a single character. Commented Mar 28, 2014 at 20:15
  • Arent the other answers enough? Seem to work Commented Mar 28, 2014 at 20:17

2 Answers 2

1

Your question is a bit unclear. This is what I'm assuming you're attempting to do (ie. ---delimiter--- is wrapped in a status):

var string = 'status1---delimiter---status1 asdf status1---delimiter---status1 asdf asdf fdsa status3---delimiter---status3 asdf status1---delimiter---status1 fdsa status1---delimiter--- asdf status5---delimiter---status5 status5---delimiter---status5 asdf status6---delimiter---status6 asdffdsa';
var matches = {}, re = /(status1|status2|status3|status4|status5|status6)---delimiter---\1/g, match;
while (match = re.exec(string)) {
    if (!matches.hasOwnProperty(match[1])) {
        matches[match[1]] = 1;
    } else {
        matches[match[1]] += 1;
    }
}
/*
 * matches = {
 *     status1: 3,
 *     status3: 1,
 *     status5: 2,
 *     status6: 1
 * }
 */
Sign up to request clarification or add additional context in comments.

Comments

1

Use strtok from this answer to iterate down the string once, pulling each "token" (status value) in turn, and increment the counts as you go.

1 Comment

That looks like what I want with some modifications, thank you.

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.