Skip to content

Instantly share code, notes, and snippets.

@tlimpanont
Last active August 29, 2015 13:57
Show Gist options
  • Save tlimpanont/9828763 to your computer and use it in GitHub Desktop.
Save tlimpanont/9828763 to your computer and use it in GitHub Desktop.
Vocabulary translation: delete keys and mapping intersected keys
if (!Array.prototype.intersect) {
Array.prototype.intersect = function (arr1) {
var r = [],
o = {}, l = this.length,
i, v;
for (i = 0; i < l; i++) {
o[this[i]] = true;
}
l = arr1.length;
for (i = 0; i < l; i++) {
v = arr1[i];
if (v in o) {
r.push(v);
}
}
return r;
};
}
if (!Object.prototype.values) {
Object.prototype.values = function (obj) {
var vals = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
vals.push(obj[key]);
}
}
return vals;
};
}
window.deleteForbiddenKeys = function (vocabulary, publisherData) {
Object.values(vocabulary).forEach(function (forbiddenKey) {
if (publisherData[forbiddenKey] !== undefined) {
delete publisherData[forbiddenKey];
}
});
return publisherData;
};
window.mapVocabulary = function (vocabulary, publisherData) {
Object.keys(vocabulary)
.intersect(Object.keys(publisherData))
.forEach(function (mappedKey) {
var value = publisherData[mappedKey];
publisherData[vocabulary[mappedKey]] = value;
delete publisherData[mappedKey];
});
return publisherData;
};
describe('Translation of Vocabulary', function () {
var vocabulary;
var publisherData;
beforeEach(function () {
vocabulary = {
"eventname": "ev",
"location": "lc"
};
publisherData = {
"eventname": "my eventname",
"location": "my location",
"site": "my site",
"lc": "my forbidden lc key"
};
});
it("should delete forbidden keys", function () {
expect(deleteForbiddenKeys(vocabulary, publisherData)).toEqual({
"eventname": "my eventname",
"location": "my location",
"site": "my site"
});
});
it("should know which keys to map", function () {
expect(
Object.keys(vocabulary).intersect(Object.keys(publisherData))
).toEqual(["eventname", "location"]);
});
it("should map the data correctly", function () {
deleteForbiddenKeys(vocabulary, publisherData);
expect(publisherData).toEqual({
"eventname": "my eventname",
"location": "my location",
"site": "my site"
});
expect(mapVocabulary(vocabulary, publisherData))
.toEqual({
"ev": "my eventname",
"lc": "my location",
"site": "my site"
});
});
});
@tlimpanont
Copy link
Author

test it with http://tryjasmine.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment