简体   繁体   English

Javascript字符串压缩

[英]Javascript string compression

I'm trying to enter a javascript competition where the script has to be <= 1kb in size. 我正在尝试进入一个javascript竞争,其中脚本的大小必须<= 1kb。 Minifying and eval is allowed, so I've run it through google's closure compiler (which does slightly better than any others I've tried). 允许缩小和评估,所以我通过谷歌的闭包编译器运行它(它比我尝试过的任何其他编译器略胜一筹)。

But I've found that if I convert the script to a string, and replace long words like 'function' and 'return' with single chars, I can reduce that even further. 但我发现,如果我将脚本转换为字符串,并用单个字符替换像'function'和'return'这样的长字,我可以进一步减少它。 Then, by embedding the string in my script, performing the substitution to restore it, and then 'evaling' it, I can get the original behaviour. 然后,通过在我的脚本中嵌入字符串,执行替换以恢复它,然后'evaling'它,我可以得到原始行为。

So I was wondering if I could generalise this last method. 所以我想知道我是否可以推广这最后一种方法。 Has anyone seen or written code to compress/decompress strings in this way? 有没有人以这种方式看到或编写压缩/解压缩字符串的代码? Feel like thinking about it? 觉得好像想一想?

EDIT To make myslelf clear, I'm asking about compressing and decompressing strings in javascript - not minifying. 编辑为了使myslelf清楚,我问的是在javascript中压缩和解压缩字符串 - 而不是缩小。 Eg how to find the most common patterns in a string, and how to write a tiny decompressor in javascript for strings where these occurences have been replaced with single chars. 例如,如何在字符串中找到最常见的模式,以及如何在javascript中编写一个微小的解压缩器,用于将这些出现的单个字符替换为单个字符串的字符串。

Thanks. 谢谢。

Do you happen to be looking for http://www.iteral.com/jscrush/ ? 您是否正在寻找http://www.iteral.com/jscrush/ I found it useful for the same competition (I assume it is js1k). 我发现它对同一场比赛很有用(我认为它是js1k)。

Have you considered shortening your code by creating a shortcut for those JavaScript objects and methods that you use a lot in your code: 您是否考虑通过为代码中使用的JavaScript对象和方法创建快捷方式来缩短代码:

var d = document; var id = d.getElementById;

And then instead of writing 而不是写作

document.getElementById("foo")

You can write 你可以写

id("foo");

标记化是压缩脚本的首选方法,因为它与各个关键字和其他名称一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM