Convert integers to a Base64-encoded VLQ string, and vice versa. No dependencies, works in node.js or browsers, supports AMD.
Sourcemaps are the most likely use case. Mappings from original source to generated content are encoded as a sequence of VLQ strings.
A variable-length quantity is a compact way of encoding large integers in text (i.e. in situations where you can't transmit raw binary data). An integer represented as digits will always take up more space than the equivalent VLQ representation:
Integer | VLQ |
---|---|
0 | A |
1 | C |
-1 | D |
123 | 2H |
123456789 | qxmvrH |
123456789123456789 | gxvh6sB |
npm install vlq
...or...
bower install vlq
...or grab the vlq.js file and include it with a <script src='vlq.js'>
tag.
vlq.encode
accepts an integer, or an array of integers, and returns a string:
vlq.encode( 123 ); // '2H';
vlq.encode([ 123, 456, 789 ]); // '2HwcqxB'
vlq.decode
accepts a string and always returns an array:
vlq.decode( '2H' ); // [ 123 ]
vlq.decode( '2HwcqxB' ); // [ 123, 456, 789 ]
vlq.encode8Bit
accepts an integer and returns a Buffer
vlq.encode8Bit( 0x7f ); // <Buffer 7f>
vlq.encode8Bit( 0x80 ); // <Buffer 81 00>
vlq.encode8Bit( 0x2000 ); // <Buffer c0 00>
vlq.decode8Bit
accepts a buffer or an array of octets and returns an integer
vlq.decode8Bit( [0x7f] ); // 0x7f
vlq.decode8Bit( [0x81, 0] ); // 0x80
vlq.decode8Bit( [0xc0, 0] ); // 0x2000
See here for an example of using vlq.js with sourcemaps.
Adapted from murzwin.com/base64vlq.html by Alexander Pavlov.
MIT.