Skip to content

Instantly share code, notes, and snippets.

@pathsny
Created June 7, 2012 21:08
Show Gist options
  • Select an option

  • Save pathsny/2891536 to your computer and use it in GitHub Desktop.

Select an option

Save pathsny/2891536 to your computer and use it in GitHub Desktop.
About toBridge
var _ = require('underscore');
function serialize(arr, object) {
if (_(arr).contains(object))
{
throw "cycle detected";
}
var szfn = _(serialize).bind(null, arr);
var innerFn = function(){
if (object.toBridge) return szfn(object.toBridge());
if (_(object).isArray()) {
return _(object).map(szfn);
}
if (_(object).isObject()) {
return _(object).reduce(function(acc, value, key){
acc[key] = szfn(value);
return acc
}, {});
}
return object;
}
arr.push(object);
var retval = innerFn();
arr.pop();
return retval;
}
How does the current toBridge handle this scenario
var bar = {}
var foo = {
bar: bar,
toBridge: function() {
return {
'bar': bar
}
}
}
bar.foo = foo;
var _ = require('underscore');
function Serializer(object) {
this._objectList = [];
this._serializedObject = this.serialize(object);
}
Serializer.prototype.serialize = function(object) {
var prev_id = this._objectList.indexOf(object);
if (prev_id !== -1) {
return {
prev_id: prev_id
}
}
var id = this.getId(object);
var retVal = object.toBridge ? object.toBridge() : object;
if (_(retVal).isArray()) return this.array(retVal, id);
if (_(retVal).isObject()) return this.object(retVal, id);
return this.scalar(retVal, id);
}
Serializer.prototype.getId = function(item) {
this._objectList.push(item);
return this._objectList.length-1;
}
Serializer.prototype.scalar = function(s, id) {
return {
id: id,
data: s
}
}
Serializer.prototype.array = function(arr, id) {
return {
id: id,
type: 'array',
data: _(arr).map(function(item) {
return this.serialize(item);
}, this)
}
}
Serializer.prototype.object = function(obj, id) {
return {
id: id,
type: 'object',
data: _(obj.toBridge ? obj.toBridge() : obj).map(function(value, key){
return {
key: key,
value: this.serialize(value)
}
},this)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment