mosceo
mosceo

Reputation: 1224

Save a big array of numbers in a cookie

I have to save 400 numbers in a cookie on the client's side. Every numbers is from 1 to 10. Any suggestions how to organize the data in the cookie to make it compact? (I'm going to work with the cookies using Python at the server side, and JavaScript at the client's side.)

Upvotes: 0

Views: 282

Answers (3)

mti2935
mti2935

Reputation: 12027

OK, if you want to do this entirely on the client side, then let's try another approach. For every three integers (from 1 to 10) that you want to store, there would be 1000 combinations (10*10*10=1000). 12 bits give you 1024 combinations (2^12=1024). So, you can store 3 integers (each 1-10) using 12 bits. So, 400 integers (each 1-10) could be stored using 1600 bits (400 / 3 * 12). The logic for storing the integers bitwise this way can be implemented easily on the client side using javascript. 1600 bits = 200 bytes (1 byte = 8 bits), so you can store 400 integers (each 1-10) using 200 bytes. This is binary data, so to store this info in a cookie, it would have to be converted to ascii text. base64 encoding is one way to do that, and this can be done client side using the functions at How can you encode a string to Base64 in JavaScript?. base64 encoding produces 4 characters for every 3 bytes encoded, so the resulting string that would be stored in the cookie would be 267 characters in length (20 * 4 / 3). The whole thing can be done this way on the client-side in javascript, and 400 integers (each 1-10) could be stored in a cookie 267 characters in length.

Upvotes: 1

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5438

Another solution would be to use `localStorage':

for(i=0; i <400; i++){
     localStorage[i] = Math.floor((Math.random()*10)+1);
}

console.log(localStorage);
alert(JSON.stringify(localStorage));

http://jsfiddle.net/S2uUn/

Upvotes: 1

mti2935
mti2935

Reputation: 12027

How about writing the list of integers to a comma-separated list, then compressing the list using gzip (which will produce binary output), then piping the binary output from gzip through a base-64 encoder, which will produce text that can be stored as a cookie. I would guess that the result would end up being only about 100 bytes in size, which can easily be stored in a cookie.

Upvotes: 0

Related Questions