Last active
December 23, 2016 19:42
-
-
Save igrek8/b2d14ffd59358bb5933235a9b7133bc6 to your computer and use it in GitHub Desktop.
nodejs simple offset helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class SmartCursor { | |
private _cur: number; | |
private _memorized: number; | |
constructor(i: number = 0) { | |
this._cur = i; | |
this._memorized = i; | |
} | |
private check(i: number) { | |
if (i < 0) { | |
throw Error('Index should not be zero or negative number'); | |
} | |
} | |
jump(i: number) { | |
this.check(i); | |
this._cur = i; | |
this._memorized = i; | |
return this; | |
} | |
diff(sync = true) { | |
const memorized = this._cur - this._memorized; | |
if (sync) { | |
this.jump(this._cur); | |
} | |
return memorized; | |
} | |
memorize() { | |
this._memorized = this._cur; | |
return this; | |
} | |
next(nextPos = 1) { | |
this.check(nextPos); | |
const clone = this._cur; | |
this._cur += nextPos; | |
return clone; | |
} | |
get memorized() { | |
return this._memorized; | |
} | |
get cur() { | |
return this._cur; | |
} | |
} | |
const pos = new SmartCursor(); | |
const buf = Buffer.from([0x01, 0x02, 0x03]); | |
buf.readUInt8(pos.next()); // => 0x01 | |
buf.readUInt16BE(pos.next(2)); // => 0x0203 | |
const readSize = pos.diff(); // => 3 bytes | |
const isBufferEnd = buf.length === pos.cur; // => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment