cube
cube

Reputation: 1802

I am trying to create a substr method with a pointer.... is there a more elegant solution?

Here's the deal. I am doing some string manipulation and I am using the substr method often. However, the way I need to use it, is more like a php fread method. Whereas, my substr needs to be guided by a pointer. The process needs to act like this:

var string='Loremipsumdolorsitamet,consectetur'

and if I read in, 'Lorem'.....as my first substr call as such:

string.substr(offset,strLenth)//0,5

then my next substr call should automatically start with an offset starting at this position in my string:

offset pointer starts here now=>ipsumdolorsitamet,consectetur'

If you haven't noticed, the offset needs to know, to start at the sixth position in the string.

Soooo... I came up with this working solution, and I want to know if it is a good solution or if anyone has any recommendations to add to it?:

var _offSetPointer=0

var _substrTest={
    _offset:function(){return _offSetPointer+=getLength}
    };  


//usage, where p is the length in bytes of the substring you want to capture.
string.substr(_substrTest._offset(getLength=p),p)

Upvotes: 5

Views: 184

Answers (1)

Cristian Sanchez
Cristian Sanchez

Reputation: 32107

var reader = function (string, offset) {
    offset = offset || 0;
    return function (n) {
        return string.substring(offset, (offset+=n||1));
    }
}

var read = reader("1234567");

read(2)
"12"

read(3)
"345"

read()
"6"

read(1)
"7"

Upvotes: 10

Related Questions