What is vlq?
The vlq npm package is used for encoding and decoding variable-length quantities (VLQs). VLQ is a universal code that uses an arbitrary number of binary octets (eight-bit bytes) to represent an arbitrarily large integer. It is used in various data serialization and compression contexts, including source map generation for web development.
What are vlq's main functionalities?
Encoding integers to VLQ
This feature allows you to encode integers into VLQ strings. The `encode` function takes an integer and returns a string representing the encoded VLQ.
"use strict"; const vlq = require('vlq'); const encoded = vlq.encode(123); console.log(encoded); // Output: '2H'
Decoding VLQ strings to integers
This feature allows you to decode VLQ strings back into integers. The `decode` function takes a VLQ-encoded string and returns an array of integers.
"use strict"; const vlq = require('vlq'); const decoded = vlq.decode('2H'); console.log(decoded); // Output: [123]
Other packages similar to vlq
base64-vlq
The base64-vlq package is similar to vlq in that it encodes and decodes VLQs, but it specifically uses Base64 encoding. This is particularly useful for source maps in web development, where compactness is crucial.
vlq-buffer
vlq-buffer is another package that provides VLQ encoding and decoding functionalities. It differs from vlq by focusing on Buffer inputs and outputs, which can be more efficient for certain Node.js applications that work with binary data.
vlq.js
Convert integers to a Base64-encoded VLQ string, and vice versa. No dependencies, works in node.js or browsers, supports AMD.
Why would you want to do that?
Sourcemaps are the most likely use case. Mappings from original source to generated content are encoded as a sequence of VLQ strings.
What is a VLQ string?
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 |
Installation
npm install vlq
Usage
Encoding
vlq.encode
accepts an integer, or an array of integers, and returns a string:
vlq.encode(123);
vlq.encode([123, 456, 789]);
Decoding
vlq.decode
accepts a string and always returns an array:
vlq.decode('2H');
vlq.decode('2HwcqxB');
Limitations
Since JavaScript bitwise operators work on 32 bit integers, the maximum value this library can handle is 2^30 - 1, or 1073741823.
Using vlq.js with sourcemaps
See here for an example of using vlq.js with sourcemaps.
Credits
Adapted from murzwin.com/base64vlq.html by Alexander Pavlov.
License
MIT.