* Dictionary.js
/**
* Created by Mch on 8/20/18.
*/
// var Set = require("./Set.js").Set;
function Dictionary() {
// Set.call();
this.items = {}
}
// Dictionary.prototype = new Set();
Dictionary.prototype.has = function(key) {
return key in this.items;
};
Dictionary.prototype.set = function(key, value) {
this.items[key] = value;
};
Dictionary.prototype.remove = function(key) {
if (this.has(key)) {
delete this.items[key];
return true;
}
return false;
};
Dictionary.prototype.get = function(key) {
return this.has(key) ? this.items[key] : undefined;
};
Dictionary.prototype.keys = function() {
var keys = [];
for (var k in this.items) {
if (this.items.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
Dictionary.prototype.values = function() {
var values = [];
for (var k in this.items) {
if (this.items.hasOwnProperty(k)) {
values.push(this.items[k]);
}
}
return values;
};
Dictionary.prototype.getItems = function() {
return this.items;
};
Dictionary.prototype.clear = function() {
this.items = {}
};
Dictionary.prototype.size = function() {
var count = 0;
for (var prop in this.items) {
if (this.items.hasOwnProperty(prop)) {
++count;
}
}
return count;
};
exports.Dictionary = Dictionary;
* TestDictionary.js
/**
* Created by Mch on 8/20/18.
*/
var Dictionary = require('./Dictionary.js').Dictionary;
function TestDictionary() {}
TestDictionary.main = function() {
var dictionary = new Dictionary();
dictionary.set('Gandalf', '[email protected]');
dictionary.set('John', '[email protected]');
dictionary.set('Tyrion', '[email protected]');
console.log(dictionary.has('Gandalf'));
console.log(dictionary.size());
console.log(dictionary.keys());
console.log(dictionary.values());
console.log(dictionary.get('Tyrion'));
dictionary.remove('John');
console.log(dictionary.keys());
console.log(dictionary.values());
console.log(dictionary.getItems());
};
TestDictionary.main();
$ node ./TestDictionary.js
true
3
[ 'Gandalf', 'John', 'Tyrion' ]
[ '[email protected]', '[email protected]', '[email protected]' ]
[email protected]
[ 'Gandalf', 'Tyrion' ]
[ '[email protected]', '[email protected]' ]
{ Gandalf: '[email protected]', Tyrion: '[email protected]' }