Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Last active December 11, 2015 01:38
Show Gist options
  • Save ryasmi/4524638 to your computer and use it in GitHub Desktop.
Save ryasmi/4524638 to your computer and use it in GitHub Desktop.
Demo of how foreign keys are not required to link objects in Python and JavaScript because of Object references.
var x, y, Xs, Ys;
// Assign objects.
x = {
"id": 0,
"Ys": []
};
y = {
"id": 0,
"Xs": []
};
// Add references.
y.Xs.push(x);
y.Xs[0].Ys.push(y);
// Remove references (reverse the addition).
Xs = y.Xs
Ys = Xs[Xs.indexOf(x)].Ys
Ys.splice(Ys.indexOf(y), 1);
Xs.splice(Xs.indexOf(x), 1);
# Assign objects.
x = {
"id": 0,
"Ys": []
}
y = {
"id": 0,
"Xs": []
}
# Add references.
y["Xs"].append(x)
y["Xs"][0]["Ys"].append(y)
# Remove references (reverse the addition).
Xs = y["Xs"]
Ys = Xs[Xs.index(x)]["Ys"]
del Ys[Ys.index(y)]
del Xs[Xs.index(x)]
// This solution reduces the number of globals using an IIFE.
var x, y;
// Assign objects.
x = {
"id": 0,
"Ys": []
};
y = {
"id": 0,
"Xs": []
};
// Add references.
y.Xs.push(x);
y.Xs[0].Ys.push(y);
// Remove references (reverse the addition).
(function (x, y) {
var Xs = y.Xs,
Ys = Xs[Xs.indexOf(x)].Ys;
Ys.splice(Ys.indexOf(y), 1);
Xs.splice(Xs.indexOf(x), 1);
}(x, y));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment