Last active
September 19, 2018 15:19
-
-
Save SethVandebrooke/b8a6c24c2c6633b8497dde2bc7870218 to your computer and use it in GitHub Desktop.
Map keys and values (keys being subjects and values being states that the subjects are in) and compress the mappings into small strings that can be decompressed into the original javacript object.
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
function StateMapper(subjects,states) { | |
var self = this; | |
self.states = states || []; | |
self.subjects = subjects || []; | |
self.encode = function(z) { | |
z = z.toString(); | |
var x = "0123456789"; | |
var u = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!?"; | |
var s = x.length; | |
var d = u.length; | |
var v = 0; | |
var n = z.length; | |
for (var i = 0; i < n; i++) { | |
v = v * s + x.indexOf(z.charAt(i)); | |
} | |
if (v < 0) return 0; | |
var r = v % d; | |
var c = u.charAt(r); | |
var q = Math.floor(v / d); | |
while (q) { | |
r = q % d; q = Math.floor(q / d); c = u.charAt(r) + c; | |
} | |
return c; | |
}; | |
self.decode = function(z) { | |
z = z.toString(); | |
var u = "0123456789"; | |
var x = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!?"; | |
var s = x.length; | |
var d = u.length; | |
var v = 0; | |
var n = z.length; | |
for (var i = 0; i < n; i++) { | |
v = v * s + x.indexOf(z.charAt(i)); | |
} | |
if (v < 0) return 0; | |
var r = v % d; | |
var c = u.charAt(r); | |
var q = Math.floor(v / d); | |
while (q) { | |
r = q % d; q = Math.floor(q / d); c = u.charAt(r) + c; | |
} | |
return c; | |
}; | |
self.compress = function (data) { | |
var str = ""; | |
for (var k in data) { | |
var v = data[k]; | |
if (!self.states.includes(v)) { | |
self.states.push(v); | |
} | |
if (!self.subjects.includes(k)) { | |
self.subjects.push(k); | |
} | |
str += self.encode(self.states.indexOf(v)); | |
} | |
return self.code = self.encode(str); | |
}; | |
self.decompress = function (code) { | |
code = code || self.code; | |
if (!code) return ; | |
var states = self.decode(code); | |
if (states.length < self.subjects.length) { | |
var l = self.subjects.length - states.length; | |
for (var i = 0; i < l; i++) { | |
states = "0" + states; | |
} | |
} | |
states = states.split(""); | |
var out = {}; | |
states.forEach(function(state,index){ | |
out[self.subjects[index]] = self.states[parseInt(state)]; | |
}); | |
return out; | |
}; | |
} | |
/* | |
var sm = new StateMapper(["bob","joe","billy","boe"],["happy","sad","mad"]); | |
sm.compress({ bob: "happy", joe: "sad", billy: "mad", boe: "happy" }); // "1X" | |
sm.decompress("1X"); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment