Last active
May 15, 2016 13:02
-
-
Save unicornist/86df680bd16354a7c71dd6012538a4ed to your computer and use it in GitHub Desktop.
simulator of PHP `serialize` function in pure JavaScript
This file contains 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 phpSerialize(obj){ // e.g. a:1{i:2;s:5:"22222";} | |
var props = []; | |
for(var prop in obj) | |
props.push(_phpSerializeVar(prop)+_phpSerializeVar(obj[prop])); | |
return 'a:'+props.length+':{'+props.join('')+'}'; | |
} | |
function _phpSerializeVar(prop){ // e.g. i:2; e.g. s:5:"22222"; | |
return (isNaN(prop) && prop.length) ? | |
's:' + prop.length + ':"' + prop + '";' : | |
'i:' + prop + ';' ; | |
} | |
console.log(phpSerialize({2: 123, '8': 'test', 'field':'value'})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment