当前位置:首页 > JavaScript

js 实现 lzw

2026-03-14 09:20:08JavaScript

LZW 压缩算法简介

LZW(Lempel-Ziv-Welch)是一种无损数据压缩算法,广泛应用于 GIF 图像格式和 Unix 的 compress 命令中。其核心思想是通过动态构建字典表,将重复出现的字符串替换为更短的编码。

js 实现 lzw

LZW 压缩实现步骤

初始化一个字典,包含所有可能的单字符作为键,并为每个键分配一个唯一的编码。

js 实现 lzw

function compress(input) {
    const dictionary = {};
    const result = [];
    let nextCode = 256;

    for (let i = 0; i < 256; i++) {
        dictionary[String.fromCharCode(i)] = i;
    }

    let current = '';
    for (const char of input) {
        const combined = current + char;
        if (combined in dictionary) {
            current = combined;
        } else {
            result.push(dictionary[current]);
            dictionary[combined] = nextCode++;
            current = char;
        }
    }

    if (current !== '') {
        result.push(dictionary[current]);
    }

    return result;
}

LZW 解压实现步骤

初始化字典与压缩时一致,但需要通过编码反向重建字符串。

function decompress(compressed) {
    const dictionary = {};
    let nextCode = 256;

    for (let i = 0; i < 256; i++) {
        dictionary[i] = String.fromCharCode(i);
    }

    let current = String.fromCharCode(compressed[0]);
    let result = current;

    for (let i = 1; i < compressed.length; i++) {
        const code = compressed[i];
        let entry;
        if (code in dictionary) {
            entry = dictionary[code];
        } else if (code === nextCode) {
            entry = current + current[0];
        } else {
            throw new Error('Invalid compressed data');
        }

        result += entry;
        dictionary[nextCode++] = current + entry[0];
        current = entry;
    }

    return result;
}

使用示例

const original = "TOBEORNOTTOBEORTOBEORNOT";
const compressed = compress(original);
const decompressed = decompress(compressed);

console.log("Original:", original);
console.log("Compressed:", compressed);
console.log("Decompressed:", decompressed);
console.log("Match:", original === decompressed);

注意事项

  • LZW 压缩效率取决于输入数据的重复模式。
  • 实际应用中可能需要处理大文件,需分块处理以避免内存问题。
  • 字典大小可能溢出,需实现动态清除或扩展机制。

标签: jslzw
分享给朋友:

相关文章

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url, f…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(f…

js钟表实现

js钟表实现

实现JavaScript钟表的基本方法 创建一个简单的JavaScript钟表可以通过以下步骤完成,涵盖数字和模拟两种形式。 数字钟表实现 HTML结构只需一个显示时间的容器: <div i…