vlq.js 2.12 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(global = global || self, factory(global.vlq = {}));
}(this, function (exports) { 'use strict';

	var charToInteger = {};
	var integerToChar = {};
	'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
	    .split('')
	    .forEach(function (char, i) {
	    charToInteger[char] = i;
	    integerToChar[i] = char;
	});
	function decode(string) {
	    var result = [];
	    var shift = 0;
	    var value = 0;
	    for (var i = 0; i < string.length; i += 1) {
	        var integer = charToInteger[string[i]];
	        if (integer === undefined) {
	            throw new Error('Invalid character (' + string[i] + ')');
	        }
	        var hasContinuationBit = integer & 32;
	        integer &= 31;
	        value += integer << shift;
	        if (hasContinuationBit) {
	            shift += 5;
	        }
	        else {
	            var shouldNegate = value & 1;
	            value >>>= 1;
	            if (shouldNegate) {
	                result.push(value === 0 ? -0x80000000 : -value);
	            }
	            else {
	                result.push(value);
	            }
	            // reset
	            value = shift = 0;
	        }
	    }
	    return result;
	}
	function encode(value) {
	    var result;
	    if (typeof value === 'number') {
	        result = encodeInteger(value);
	    }
	    else {
	        result = '';
	        for (var i = 0; i < value.length; i += 1) {
	            result += encodeInteger(value[i]);
	        }
	    }
	    return result;
	}
	function encodeInteger(num) {
	    var result = '';
	    if (num < 0) {
	        num = (-num << 1) | 1;
	    }
	    else {
	        num <<= 1;
	    }
	    do {
	        var clamped = num & 31;
	        num >>>= 5;
	        if (num > 0) {
	            clamped |= 32;
	        }
	        result += integerToChar[clamped];
	    } while (num > 0);
	    return result;
	}

	exports.decode = decode;
	exports.encode = encode;

	Object.defineProperty(exports, '__esModule', { value: true });

}));