Skip to content

Commit

Permalink
Basic Array.prototype.indexOf implementation.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn committed Jan 29, 2016
1 parent 7f1ef3e commit db1e6e7
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
exports.encode = exports.stringify = function (value) {
var values = [value];
var table = [];

for (var v = 0; v < values.length; ++v) {
value = values[v];
if (value && typeof value === "object") {
var copy = table[v] = Array.isArray(value) ? [] : {};
Object.keys(value).forEach(function (key) {
var child = value[key];
var index = values.indexOf(child);
if (index < 0) {
index = values.push(child) - 1;
}
copy[key] = index;
});
} else {
table[v] = value;
}
}

return JSON.stringify(table);
};

exports.decode = exports.parse = function (encoding) {
var table = JSON.parse(encoding);

table.forEach(function (entry) {
if (entry && typeof entry === "object") {
Object.keys(entry).forEach(function (key) {
entry[key] = table[entry[key]];
});
}
});

return table[0];
};

0 comments on commit db1e6e7

Please sign in to comment.