Skip to content
This repository was archived by the owner on Mar 30, 2022. It is now read-only.
This repository was archived by the owner on Mar 30, 2022. It is now read-only.

Have "Complex Tokens" that are length-independent... #3

Description

@TooTallNate

Would it be possible to create a custom complex token that doesn't know it's len property?

I.E. I'm trying to make a CharDelimiter custom token that works similar to String#split, and returns a token when it finds a specified Char (maybe a space, " "):

function CharDelimiter(delim) {
  this.get = function(buf, off) {
    for (var i=off, l=buf.length; i<l; i++) {
      if (buf[i] == delim.charCodeAt(0)) {
        return buf.slice(off, i-1);
      }
    }
  }
}

var stream = new EventEmitter();
strtok.parse(stream, function(v) {
  if (v === undefined) {
    return new CharDelimiter(" ");
  }

  console.error(v);
  return new CharDelimiter(" ");
});

stream.emit("data", new Buffer("this is a test"));
  //-> this
  //-> is
  //-> a
  //-> test

Looking at the current way it's set up, this might be hard to implement. And I realize that it might just be easier to implement in a new module. But frankly, I thought that some sort of way to split a token on a certain char or String would be build-in functionality, since that's how the C version kinds works.

I think it would work if the get function were allowed to return a special value (similar to DEFER, lets call it WAIT), which meant that the Buffer didn't have whatever the custom token was looking for (yet) and to re-invoke the get method after another data event is received. Then my CharDelimiter function might look something like:

function CharDelimiter(delim) {
  this.get = function(buf, off) {
    for (var i=off, l=buf.length; i<l; i++) {
      if (buf[i] == delim.charCodeAt(0)) {
        return buf.slice(off, i-1);
      }
    }
    // If we didn't find the delimiter, wait til the next 'data' event
    return strtok.WAIT;
  }
}

What are your thoughts on an API like this? Maybe even reusing the DEFER object itself, since their meaning is similar.

Thanks in advance!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions