HTML and CSS Reference
In-Depth Information
which means that if we use the right compression algorithm, we should be able to store 16 yes/
no values in it (saving 93.75% from the string method).
The problem is that JavaScript doesn't offer a built-in way to do that, so the code becomes a
bit more complicated.
Packing 16 Values Into One Character
You can use
String.fromCharCode
to get the individual characters. It accepts a numerical
value of up to 65,535 and returns a character (and for values greater than that, it returns an
empty string).
So, we have to split our string into chunks of 16 characters in size. We can
do that through
.match(/.{1,16}/g)
.
To sum up, the full solution would look like this:
7
function
pack
(
/* string */
values
) {
var
chunks
=
values
.
match
(
/.{1,16}/g
),
packed
=
''
;
for
(
var
i
=
0
;
i
<
chunks
.
length
;
i
++
) {
packed
+=
String
.
fromCharCode
(
parseInt
(
chunks
[
i
],
2
));
}
return
packed
;
}
function
unpack
(
/* string */
packed
) {
var
values
=
''
;
for
(
var
i
=
0
;
i
<
packed
.
length
;
i
++
) {
values
+=
packed
.
charCodeAt
(
i
).
toString
(
2
);
}
return
values
;
}
It wasn't that hard, was it?
With these few lines of code, you can pack the aforementioned 512 values into—drum roll,
please—
32 characters (64 bytes)
!
Quite an improvement over our original 2 KB (with the array method), isn't it?