Skip to content

Instantly share code, notes, and snippets.

@pgaskin
Last active January 11, 2026 07:08
Show Gist options
  • Select an option

  • Save pgaskin/35c55a9186abb752d353d2cb3681836a to your computer and use it in GitHub Desktop.

Select an option

Save pgaskin/35c55a9186abb752d353d2cb3681836a to your computer and use it in GitHub Desktop.
Ultra-compact lzstring decompress implementation.
function decompress(buf) {
const fromCharCode = String.fromCharCode
const invalid = new Error("invalid")
let idx = 0, u16 = 0, bit = 0
const uint = bits => {
let res = 0
for (let i = 0; i < bits; i++) {
if (bit == 0) {
if (idx >= buf.length) {
throw invalid // unexpected end of stream
}
bit = 1<<(16-1)
u16 = buf.charCodeAt(idx++)
}
if (u16 & bit) {
res |= 1 << i
}
bit >>= 1
}
return res
}
let last, dict = [], res = ""
for (;;) {
const dictSize = dict.length
const bits = 32-Math.clz32(3+dictSize)
let op = uint(bits)
if (op == 2) {
return res
}
let chunk
if (op > 2) {
op -= 3
if (!last || op > dictSize) {
throw invalid // first packet must be a literal || dictionary index out of range
}
if (op < dictSize) {
chunk = dict[op]
} else {
chunk = last + last.charAt(0)
}
} else {
chunk = fromCharCode(uint(op?16:8))
dict.push(chunk)
}
if (last) {
dict.push(last + chunk.charAt(0))
}
last = chunk
res += chunk
}
}
function decompress(r){let t=String.fromCharCode,e=Error("invalid"),h=0,o=0,f=0,i=t=>{let i=0;for(let l=0;l<t;l++){if(0==f){if(h>=r.length)throw e;f=32768,o=r.charCodeAt(h++)}o&f&&(i|=1<<l),f>>=1}return i},l,n=[],a="";for(;;){let r,h=n.length,o=i(32-Math.clz32(3+h));if(2==o)return a;if(o>2){if(o-=3,!l||o>h)throw e;r=o<h?n[o]:l+l.charAt(0)}else r=t(i(o?16:8)),n.push(r);l&&n.push(l+r.charAt(0)),l=r,a+=r}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment