Skip to content

Instantly share code, notes, and snippets.

@ax2mx
Created June 23, 2022 20:25
Show Gist options
  • Select an option

  • Save ax2mx/ec68e39f22efaa0188c652a3175f0819 to your computer and use it in GitHub Desktop.

Select an option

Save ax2mx/ec68e39f22efaa0188c652a3175f0819 to your computer and use it in GitHub Desktop.
Simple object serializer
const serialize = (obj) => {
const type = typeof obj;
if (obj === null) return 'null';
else if (type === 'string') return `'${obj}'`;
else if (type === 'number') return obj.toString();
else if (type === 'boolean') return obj.toString();
else if (type !== 'object') return obj.toString();
else if (Array.isArray(obj)) {
return `[${obj}]`;
} else {
let s = '{';
for (const key in obj) {
const value = obj[key];
if (s.length > 1) s += ',';
s += key + ':' + serialize(value);
}
return s + '}';
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment