Last active
January 26, 2016 19:16
-
-
Save proprietary/70da12cd03aae91e6fe8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Apache2.0 license | |
// Copyright (c) 2016 Zeleke Snyder | |
import { chunk } from 'lodash' | |
export const packIntoStr = function ([...bytes]) { | |
// Pack bytes into string | |
var bytesLen = bytes.length | |
var m = 4 - (bytesLen % 4) // remaining to make it fit | |
if (m !== 0) { | |
// append to bytes to make it fit | |
bytes = bytes.concat(Array(m).fill(bytesLen)) // last byte is array len | |
} else { | |
bytes = bytes.concat(Array(4).fill(bytesLen)) // ensure last byte is array len | |
} | |
let chunks = chunk(bytes, 4) // split into 4 bytes each | |
// do the packing | |
return chunks.map(fourBytes => { | |
return fourBytes.reduce((x, y, i) => { | |
x |= (y & 0xff) << (8 * i) | |
return x | |
}) | |
}) | |
.map(packed => packed.toString(36)) // store as base-36 strings | |
.join('#') // finally store as one string | |
} | |
export const unpackFromStr = function (str) { | |
// Unpack bytes as array from base-36 string | |
return str.split('#') | |
.map(s => { | |
let v = parseInt(s, 36) | |
return [ | |
v & 0xff, | |
(v >> 8) & 0xff, | |
(v >> 16) & 0xff, | |
(v >> 24) & 0xff | |
] | |
}) | |
.reduce((x, y) => x.concat(y)) | |
.filter((z, i, a) => { | |
const arrLen = a[a.length - 1] // actual array length is stored as last value | |
return i < arrLen | |
}) | |
} | |
/* | |
* Example: | |
* var a = packIntoStr([1,2,3,4,5,6,7,8]) // '142lmp#286m85#28816w' | |
* var b = unpackFromStr(a) // [ 1, 2, 3, 4, 5, 6, 7, 8 ] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment