I have this object:
function formBuddy()
{
var fields = new Array();
var labels = new Array();
var rules = new Array();
var count=0;
this.addField = function(field, label, rule)
{
fields[count] = field;
labels[field] = label;
rules[field] = rule;
count = ++count;
}
}
Its used in this way:
var cForm=new formBuddy();
cForm.addField("c_first_name","First Name","required");
cForm.addField("c_last_name","Last Name","required");
The problem is, in the addField() function the fields array is being set correct (perhaps because a numerical index is being used to refer to it) but the other 2 arrays (labels and rules) aren't being touched at all. Doing a console.log shows them as empty in firebug.
What do I need to change to make them work? I'd still like to refer to the rules and labels by the string index of the field.
Use objects instead:
function formBuddy()
{
var fields = {};
var labels = {};
var rules = {};
var count = 0;
this.addField = function(field, label, rule)
{
fields[count] = field;
labels[field] = label;
rules[field] = rule;
count++;
}
}
But as Christoph already mentioned, I would store this information in a single data structure too. For example:
function formBuddy() {
var fields = {};
this.addField = function(name, label, rule) {
fields[name] = {
name: name,
label: label,
rule: rule
};
};
this.getField = function(name) {
return fields[name];
};
}
var cForm=new formBuddy();
cForm.addField("c_first_name","First Name","required");
cForm.addField("c_last_name","Last Name","required");
alert(cForm.getField("c_last_name").label);
fields should be an array, whereas labels and rules should be objects as you want to use strings as keys. Also, addField() is the same for each instance of FormBuddy() (names of constructor functions should be capitalized) and should reside in the prototype, ie
function FormBuddy() {
this.fields = []; // this is the same as `new Array()`
this.labels = {}; // this is the same as `new Object()`
this.rules = {};
}
FormBuddy.prototype.addField = function(field, label, rule) {
this.fields.push(field);
this.labels[field] = label;
this.rules[field] = rule;
};
You can access the labels/rules via
var buddy = new FormBuddy();
buddy.addField('foo', 'bar', 'baz');
alert(buddy.labels['foo']);
alert(buddy.rules.foo);
Just to further enrage Luca ;), here's another version which also dosn't encapsulate anything:
function FormBuddy() {
this.fields = [];
}
FormBuddy.prototype.addField = function(id, label, rule) {
var field = {
id : id,
label : label,
rule : rule
};
this.fields.push(field);
this['field ' + id] = field;
};
FormBuddy.prototype.getField = function(id) {
return this['field ' + id];
};
var buddy = new FormBuddy();
buddy.addField('foo', 'label for foo', 'rule for foo');
It's similar to Gumbo's second version, but his fields object is merged into the FormBuddy instance. An array called fields is added instead to allow for fast iteration.
To access a field's label, rule, or id, use
buddy.getField('foo').label
To iterate over the fields, use
// list rules:
for(var i = 0, len = buddy.fields.length; i < len; ++i)
document.writeln(buddy.fields[i].rule);
Arrays are treated as Objects in Javascript, therefore your piece of code works, it's just that firebug's console.log isn't showing you the "Objects" inside the array, rather just the array values ...
Use the for(var i in obj) to see what objects values the Array contains:
function formBuddy() {
var fields = new Array();
var labels = new Array();
var rules = new Array();
var count=0;
this.addField = function(field, label, rule)
{
fields[count] = field;
labels[field] = label;
rules[field] = rule;
count = ++count;
for(var i in labels) {
console.log(labels[i]);
}
for(var i in rules) {
console.log(rules[i]);
}
console.log(labels.c_last_name);
// or
console.log(labels["c_last_name"]);
}
}
var cForm = new formBuddy();
cForm.addField("c_last_name","Last Name","required");
Is this an alternative to what you are seeking ?
Try it.
<script type="text/javascript">"use strict";
function formBuddy() {
this.fields = new Array();
this.labels = new Array();
this.rules = new Array();
this.count=0;
this.addField = function(field, label, rule)
{
this.fields[this.count] = field;
this.labels[field] = label;
this.rules[field] = rule;
this.count++;
}
}
var cForm = new formBuddy();
// FILLING IN THE DATABASE
cForm.addField("c_first_name","Diasoluka","duplicated");
cForm.addField("c_Middle_name","Nz","inspect");
cForm.addField("c_last_name","Luyalu","mandatory");
cForm.addField("c_first_name","Diasoluka","duplicated");
console.log(`ACCESSING EACH PROPERTY INDIVIDUALLY\n,${'.'.repeat(31)}`);
let el=Object.entries(cForm.fields); // DESTRUCTURING
console.log(Object.is(el,Object.entries(cForm.fields)));
// false
const [f1,f2,f3] = el; // DESTRUCTURING=DÉCOMPOSITION
console.log("FIELDS:\n",f1," | ",f2," | ",f3,"\n\n");
// FIELDS:
// Array [ "0", "c_first_name" ]
// Array [ "1", "c_Middle_name" ]
// Array [ "2", "c_last_name" ]
let labels = Object.entries(cForm.labels); // DESTRUCTURING
const [l1,l2,l3] = labels; // DESTRUCTURING
console.log("LABELS:\n",l1," | ",l2," | ",l3,"\n\n");
// LABELS:
// Array [ "c_first_name", "Diasoluka" ]
// Array [ "c_Middle_name", "Nz" ]
// Array [ "c_last_name", "Luyalu" ]
let rules = Object.entries(cForm.rules); // DESTRUCTURING
const [r1,r2,r3] = rules; // DESTRUCTURING
console.log("RULES:\n",r1," | ",r2," | ",r3,"\n\n");
// RULES:
// Array [ "c_first_name", "duplicated" ]
// Array [ "c_Middle_name", "inspect" ]
// Array [ "c_last_name", "mandatory" ]
console.log(`PAESING THE DATABASE =\nACCESSING ALL THE FIELDS AT ONCE\n,${'.'.repeat(31)}`);
for(let key in cForm.fields){
let el=cForm.fields[key]; // ASSIGNMENT=AFFECTATION
console.log(Object.is(el,cForm.fields[key]));
// true true true true
console.log(`${el} // ${cForm.labels[el]} // ${cForm.rules[el]}\n`);
}
// c_first_name // Diasoluka // duplicated
// c_Middle_name // Nz // inspect
// c_last_name // Luyalu // mandatory
// c_first_name // Diasoluka // duplicated
console.log("\n");
console.log(`THE INNER STRUCTURE OF OUR cForm OBJECT\n,${'.'.repeat(31)}`);
console.log(Object.entries(cForm)); // DESTRUCTURING
// (5) [Array(2), Array(2), Array(2), Array(2), Array(2)]
// 0: (2) ['fields', Array(4)]
// 1: (2) ['labels', Array(0)]
// 2: (2) ['rules', Array(0)]
// 3: (2) ['count', 4]
// 4: (2) ['addField', ƒ]
// length: 5
// [[Prototype]]: Array(0)
</script>
Related
I have a class called Terminal which can receive a group of arguments from multiple instances.
Every time when Terminal gets the arguments, a new object called this.cells stores them, and push it into a new Array called this.mesh.
My goal is to call all of the properties on same column no matter how I named to call them.
So when if I type console.log(this.mesh.location), a result would be like this:
23 // Person | constructor(name, age, gender) |
New York // Job | constructor(name, location, salary) |
20 // Angle | constructor(name, size, color) |
//---------------------+-------------------------------------+
// All values showed up because these properties were on the same column
A problem is the first array can't find rest of the objects except the first one ([0]) even the console shows all 3 objects like this:
But if I inspect this.mesh[1], the first array is giving undefined:
The 3 objects must be inside each of the arrays so that I can compare those keys and select the specific values using Hashtable or Proxy.
Any solutions to fix this problem?
This is my code:
// person.mjs
import Terminal from './terminal.mjs';
class Person {
constructor(name, age, gender, input) {
this.name = name;
this.age = age;
this.gender = gender;
this.input = input || new Terminal(this);
// console.log(this.input.name);
// this.input.event();
}
}
let p1 = new Person('James', 23, 'Male');
// job.mjs
import Terminal from './terminal.mjs';
class Job {
constructor(name, location, salary, input) {
this.name = name;
this.location = location;
this.salary = salary
this.input = input || new Terminal(this);
// console.log(this.input.name);
}
}
let a1 = new Job('Web Developer', 'New York', 40000);
// shape.mjs
import Terminal from './terminal.mjs';
class Shape {
constructor(name, size, color, input) {
this.name = name;
this.size = size;
this.color = color;
this.input = input || new Terminal(this);
}
}
let s1 = new Shape('Triangle', 20, 'Blue');
// terminal.mjs
export default class Terminal {
constructor(...output) {
/* Define an Array */
this.mesh = Array.prototype;
/* Assign, insert a group of contents to a new object */
this.cells = Object.assign({}, ...output);
/* able to call the specific variables from the other js files. */
/* can call the variable without [] notation. */
this.pylon = Object.assign(Object.prototype, ...output);
/* Put it into the Array */
this.mesh.push(this.cells);
/* consoling */
// console.log(this.mesh[1]) // Gives undefined the first array.
console.log(this.mesh.location);
}
}
Attempt 1
According to Jonas' answer, but I can't get a rest of values because this.mesh does not stack the objects into the 1 array.
If I console.log(this.mesh); the browser throws this result:
[{…}] terminal0.mjs:14
[{…}] terminal0.mjs:14
[{…}] terminal0.mjs:14
export default class Terminal {
constructor(...output) {
this.log = console.log('------------------');
/* Array */
this.mesh = [];
/* Assign the objects */
this.cells = Object.assign({}, ...output);
/* Push it into the Array */
this.mesh.push(this.cells);
/* Proxy */
this.bridge.age;
}
get bridge() {
let handler = {
get(target, property, receiver) {
let value = Object.keys(target[0]).indexOf(property);
target.map(object => {
let refined = Object.values(object)[value];
console.log(refined);
})
}
}
return new Proxy(this.mesh, handler);
}
}
Attempt 2
This time I've used async for collecting the objects but it gives the same result my original question.
export default class Terminal {
constructor(...output) {
this.output = output;
this.bridge();
}
async bridge() {
let getObjects = new Promise((res, rej) => {
this.mesh = Array.prototype;
this.cells = Object.assign({}, ...this.output);
this.mesh.push(this.cells);
res(this.mesh);
}),
patch = await getObjects;
console.log(this.mesh[1]);
}
}
First of all you are trying to instantiate new Terminal(this) multiple time, By doing that every time new instance of Terminal class invoked you loos other context and also have side effects.
My opinion is use a singleton method for terminal.js. Example below
// terminal.js
class Terminal {
constructor() {
this.cells = [];
this.mesh = [];
}
get(propName) {
try {
//Define the variable to store the index position of cells
let finalIndex = "";
//Find the index position of the property
this.cells.forEach(cell => {
let index = cell.indexOf(propName);
if (index !== -1) {
finalIndex = index;
}
});
//Check if the finalIndex is there
if (finalIndex >= 0) {
//Find the values by index
const finalData = this.mesh.map(data => data[finalIndex]);
console.log(finalData);
} else {
throw new Error(`No property named ${propName} found!`);
}
} catch (msg) {
console.error(msg);
}
}
set(...output) {
//Create a new ref object
const data = Object.assign({}, ...output);
//Set the keys in a 2-D array structure
this.cells.push(Object.keys(data));
//Set the values in a 2-D array structure
this.mesh.push(Object.values(data));
}
}
const instance = new Terminal();
// Singleton
Object.freeze(instance);
module.exports = instance;
index.js
var Terminal = require("./terminal.js");
require("./job");
require("./person");
require("./shape");
Terminal.get("location"); // [ 'New York', 23, 20 ]
Terminal.get("name"); // [ 'Web Developer', 'James', 'Triangle' ]
Terminal.get("gender"); // [ 40000, 'Male', 'Blue' ]
Here is the sample code which solved your problem.
https://repl.it/#pandasanjay/stackoverflow-57900065
const data = [{ a: 1, b: 2 }, { c: 1, d: 2 }];
const position = Object.keys(data[0]).indexOf("a");
const result = data.map(obj => Object.values(obj)[position]);
You can use Object.keys and Object.values to access the object keys/values as arrays.
As a sidenote, this:
/* Define an Array */
this.mesh = Array.prototype;
Makes litlle sense. No new array gets created. Also the comment says exactly the same as the line below. Just do
this.mesh = [];
Here is my code:
var subMed = [ {med:'bm', sub:[ 'a' , 'b' ]} , {med:'bm', sub:[ 'c' , 'd' , 'e' ]} ];
var sal = [ {num:"1",amount:"500"} ];
var t = {Class:"1", subMeds:subMed, numOfSub:2, sals:sal };
var infoAcademic = [];
infoAcademic.push(t);
subMed = [ {med:'em', sub:[ 'p']} , {med:'bm', sub:[ 'r' , 's' ]} ];
sal = [ {num:"2",amount:"1500"},{num:"1",amount:"700"} ];
t = {Class:"1", subMeds:subMed, numOfSub:1, sals:sal };
infoAcademic.push(t);
var tempObj = infoAcademic[1]; // an object
var mediumSubjects = tempObj["subMeds"]; // an array
console.log(mediumSubjects);
for(i=0;i<mediumSubjects.length;i++){
var temp = {}; // object
temp = mediumSubjects[i];
if(temp["med"] == 'bm'){
tempObj["numOfSub"] = tempObj["numOfSub"] - temp["sub"].length;
var salArr = tempObj["sals"]; // array
var j = salArr.length;
if(salArr.length > 0){
while(j--){
var salObj = salArr[j]; // object
var howManySub = salObj["num"];
if(howManySub > tempObj["numOfSub"]){
salArr.splice(j,1);
}
}
}
console.log("removing from the medSubjects list: ");
console.log(temp);
var removed = mediumSubjects.splice(i, 1);
break;
}
}
console.log("removed element: ");
console.log(removed);
console.log(mediumSubjects);
When I write this code this an online js editor https://js.do/ , the code gives result as per expected. But when I incorporate this code in a onclick function of my JSP page, no element gets removed from the mediumSubjects array. The removed element shows empty.
However, when I comment out this portion:
tempObj["numOfSubj"] = tempObj["numOfSub"] - temp["sub"].length;
var salArr = tempObj["sals"]; // array
var j = salArr.length;
if(salArr.length > 0){
while(j--){
var salObj = salArr[j]; // object
var howManySub = salObj["num"];
if(howManySub > tempObj["numOfSub"]){
salArr.splice(j,1);
}
}
}
the code surprisingly behaves as expected- it removes the element from the mediumSubjects array.
Is there any synchronization issue or something else? Why this sort of unusual behavior?
N.B. I need to remove elements from the array mediumSubjects, so delete won't work here.
Try this variant:
var newMedSub = medSub.filter(function(elem) {
return elem.med !== 'em';
});
It will help you to get a new array without unnessessary object.
All you actually need is to iterate over the outer array and in the body of this loop you need to iterate over the object keys.
for Example:
// removing med key from the array.
medSub.forEach(obj => {
for (let key in obj) {
if (key === 'med' && obj[key] === 'em') {
delete obj[key];
}
}
});
I hope this helps.
First of all: I already found this thread, which basically is exactly what I want, but I tried my best to apply it to my needs - I couldn't.
So, I have the following javascript function:
function loadRelationData(object) {
var result = [];
var parents = []
parents = getParentObjectsByObjectID(object['ObjectID']);
var tmpFirstObjects = [];
var tmpOtherObjects = [];
$.each(parents, function (_, parent) {
var keyName = 'Übergeordnete ' + parent['ObjectType'];
var pushObject = {};
if (parent['ObjectType'] == object['ObjectType']) {
pushObject['Fieldname'] = keyName;
pushObject['Value'] = parent['Name'];
tmpFirstObjects.push(pushObject);
} else {
pushObject['Fieldname'] = keyName;
pushObject['Value'] = parent['Name'];
tmpOtherObjects.push(pushObject);
}
});
result = result.concat(tmpFirstObjects).concat(tmpOtherObjects);
return result;
}
The parents array looks like this
And my function creates this result
This might be a bit complicated, but I need to split it up like this, because I need the order.
What I want is an array with both "TEC_MapLocations" joined together like this:
[
{Fieldname: 'Übergeordnete TEC_Equipment', Value: 'E0192'},
{Fieldname: 'Übergeordnete TEC_MapLocation', Value: ['M100', 'M200']},
{Fieldname: 'Übergeordnete TEC_FunctionalLocation', Value: 'FL456'}
]
Any ideas on how to alter my code to achieve the desired result right away or how to merge the results array?
edit: I used Joseph's solution and used the following (quick and dirty) sort function to get back my desired sorting:
output.sort(function (a, b) {
if (a.ObjectType == object.ObjectType) {
return -1
} else {
return 1
}
});
What you'd want to do first is build a hash with Fieldname as key, and an array as value. Then you'd want to use reduce to add the values into the hash and array. Then you can transform it into an array using Object.keys and map.
var input = [
{Name: 'M100', ObjectID: 1, ObjectType: 'TEC_MapLocation'},
{Name: 'M200', ObjectID: 2, ObjectType: 'TEC_MapLocation'},
{Name: 'FL456', ObjectID: 4, ObjectType: 'TEC_FunctionalLocation'},
{Name: 'E0192', ObjectID: 5, ObjectType: 'TEC_Equipment'}
];
var hash = input.reduce(function(carry, item){
// Create the name
var name = 'Übergeordnete ' + item.ObjectType;
// If array with name doesn't exist, create it
if(!carry[name]) carry[name] = [];
// If item isn't in the array, add it.
if(!~carry[name].indexOf(item.Name)) carry[name].push(item.Name);
return carry;
}, {});
// Convert the hash into an array
var output = Object.keys(hash).map(function(key, index, array){
return { Fieldname: key, Value: hash[key] }
});
document.write(JSON.stringify(output));
Try this:
function joinObjects( array ) {
// Start with empty array
var ret = new Array();
// Iterate array
for ( var i = 0; i < array.length; i++ ) {
// Search by fieldname
var match = false;
var j;
for ( j = 0; j < ret.length; j++ ) {
if ( array[i].Fieldname == ret[j].Fieldname ) { match = true; break; }
}
// If not exists
if ( !match ) {
// Intert object
ret.push({
Fieldname: array[i].Fieldname,
Value: new Array()
});
}
// Insert value
ret[j].Value.push( array[i].Value );
}
// Return new array
return ret;
}
http://jsfiddle.net/6entfv4x/
I need to know if one or more duplicates exist in a list. Is there a way to do this without travelling through the list more than once?
Thanks guys for the suggestions. I ended up using this because it was the simplest to implement:
var names = [];
var namesLen = names.length;
for (i=0; i<namesLen; i++) {
for (x=0; x<namesLen; x++) {
if (names[i] === names[x] && (i !== x)) {alert('dupe')}
}
}
Well the usual way to do that would be to put each item in a hashmap dictionary and you could check if it was already inserted. If your list is of objects they you would have to create your own hash function on the object as you would know what makes each one unique. Check out the answer to this question.
JavaScript Hashmap Equivalent
This method uses an object as a lookup table to keep track of how many and which dups were found. It then returns an object with each dup and the dup count.
function findDups(list) {
var uniques = {}, val;
var dups = {};
for (var i = 0, len = list.length; i < len; i++) {
val = list[i];
if (val in uniques) {
uniques[val]++;
dups[val] = uniques[val];
} else {
uniques[val] = 1;
}
}
return(dups);
}
var data = [1,2,3,4,5,2,3,2,6,8,9,9];
findDups(data); // returns {2: 3, 3: 2, 9: 2}
var data2 = [1,2,3,4,5,6,7,8,9];
findDups(data2); // returns {}
var data3 = [1,1,1,1,1,2,3,4];
findDups(data3); // returns {1: 5}
Since we now have ES6 available with the built-in Map object, here's a version of findDups() that uses the Map object:
function findDups(list) {
const uniques = new Set(); // set of items found
const dups = new Map(); // count of items that have dups
for (let val of list) {
if (uniques.has(val)) {
let cnt = dups.get(val) || 1;
dups.set(val, ++cnt);
} else {
uniques.add(val);
}
}
return dups;
}
var data = [1,2,3,4,5,2,3,2,6,8,9,9];
log(findDups(data)); // returns {2 => 3, 3 => 2, 9 => 2}
var data2 = [1,2,3,4,5,6,7,8,9];
log(findDups(data2)); // returns empty map
var data3 = [1,1,1,1,1,2,3,4];
log(findDups(data3)); // returns {1 => 5}
// display resulting Map object (only used for debugging display in snippet)
function log(map) {
let output = [];
for (let [key, value] of map) {
output.push(key + " => " + value);
}
let div = document.createElement("div");
div.innerHTML = "{" + output.join(", ") + "}";
document.body.appendChild(div);
}
If your strings are in an array (A) you can use A.some-
it will return true and quit as soon as it finds a duplicate,
or return false if it has checked them all without any duplicates.
has_duplicates= A.some(function(itm){
return A.indexOf(itm)===A.lastIndexOf(itm);
});
If your list was just words or phrases, you could put them into an associative array.
var list=new Array("foo", "bar", "foobar", "foo", "bar");
var newlist= new Array();
for(i in list){
if(newlist[list[i]])
newlist[list[i]]++;
else
newlist[list[i]]=1;
}
Your final array should look like this:
"foo"=>2, "bar"=>2, "foobar"=>1
I need to store some statistics using JavaScript in a way like I'd do it in C#:
Dictionary<string, int> statistics;
statistics["Foo"] = 10;
statistics["Goo"] = statistics["Goo"] + 1;
statistics.Add("Zoo", 1);
Is there an Hashtable or something like Dictionary<TKey, TValue> in JavaScript?
How could I store values in such a way?
Use JavaScript objects as associative arrays.
Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index.
Create an object with
var dictionary = {};
JavaScript allows you to add properties to objects by using the following syntax:
Object.yourProperty = value;
An alternate syntax for the same is:
Object["yourProperty"] = value;
If you can, also create key-to-value object maps with the following syntax:
var point = { x:3, y:2 };
point["x"] // returns 3
point.y // returns 2
You can iterate through an associative array using the for..in loop construct as follows
for(var key in Object.keys(dict)){
var value = dict[key];
/* use key/value for intended purpose */
}
var associativeArray = {};
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
If you are coming from an object-oriented language you should check this article.
All modern browsers support a JavaScript Map object. There are a couple of reasons that make using a Map better than Object:
An Object has a prototype, so there are default keys in the map.
The keys of an Object are Strings, where they can be any value for a Map.
You can get the size of a Map easily while you have to keep track of size for an Object.
Example:
var myMap = new Map();
var keyObj = {},
keyFunc = function () {},
keyString = "a string";
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");
myMap.size; // 3
myMap.get(keyString); // "value associated with 'a string'"
myMap.get(keyObj); // "value associated with keyObj"
myMap.get(keyFunc); // "value associated with keyFunc"
If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.
Unless you have a specific reason not to, just use a normal object. Object properties in JavaScript can be referenced using hashtable-style syntax:
var hashtable = {};
hashtable.foo = "bar";
hashtable['bar'] = "foo";
Both foo and bar elements can now then be referenced as:
hashtable['foo'];
hashtable['bar'];
// Or
hashtable.foo;
hashtable.bar;
Of course this does mean your keys have to be strings. If they're not strings they are converted internally to strings, so it may still work. Your mileage may vary.
Since every object in JavaScript behaves like - and is generally implemented as - a hashtable, I just go with that...
var hashSweetHashTable = {};
In C# the code looks like:
Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);
or
var dictionary = new Dictionary<string, int> {
{"sample1", 1},
{"sample2", 2}
};
In JavaScript:
var dictionary = {
"sample1": 1,
"sample2": 2
}
A C# dictionary object contains useful methods, like dictionary.ContainsKey()
In JavaScript, we could use the hasOwnProperty like:
if (dictionary.hasOwnProperty("sample1"))
console.log("sample1 key found and its value is"+ dictionary["sample1"]);
If you require your keys to be any object rather than just strings, then you could use my jshashtable.
Note:
Several years ago, I had implemented the following hashtable, which has had some features that were missing to the Map class. However, that's no longer the case — now, it's possible to iterate over the entries of a Map, get an array of its keys or values or both (these operations are implemented copying to a newly allocated array, though — that's a waste of memory and its time complexity will always be as slow as O(n)), remove specific items given their key, and clear the whole map.
Therefore, my hashtable implementation is only useful for compatibility purposes, in which case it'd be a saner approach to write a proper polyfill based on this.
function Hashtable() {
this._map = new Map();
this._indexes = new Map();
this._keys = [];
this._values = [];
this.put = function(key, value) {
var newKey = !this.containsKey(key);
this._map.set(key, value);
if (newKey) {
this._indexes.set(key, this.length);
this._keys.push(key);
this._values.push(value);
}
};
this.remove = function(key) {
if (!this.containsKey(key))
return;
this._map.delete(key);
var index = this._indexes.get(key);
this._indexes.delete(key);
this._keys.splice(index, 1);
this._values.splice(index, 1);
};
this.indexOfKey = function(key) {
return this._indexes.get(key);
};
this.indexOfValue = function(value) {
return this._values.indexOf(value) != -1;
};
this.get = function(key) {
return this._map.get(key);
};
this.entryAt = function(index) {
var item = {};
Object.defineProperty(item, "key", {
value: this.keys[index],
writable: false
});
Object.defineProperty(item, "value", {
value: this.values[index],
writable: false
});
return item;
};
this.clear = function() {
var length = this.length;
for (var i = 0; i < length; i++) {
var key = this.keys[i];
this._map.delete(key);
this._indexes.delete(key);
}
this._keys.splice(0, length);
};
this.containsKey = function(key) {
return this._map.has(key);
};
this.containsValue = function(value) {
return this._values.indexOf(value) != -1;
};
this.forEach = function(iterator) {
for (var i = 0; i < this.length; i++)
iterator(this.keys[i], this.values[i], i);
};
Object.defineProperty(this, "length", {
get: function() {
return this._keys.length;
}
});
Object.defineProperty(this, "keys", {
get: function() {
return this._keys;
}
});
Object.defineProperty(this, "values", {
get: function() {
return this._values;
}
});
Object.defineProperty(this, "entries", {
get: function() {
var entries = new Array(this.length);
for (var i = 0; i < entries.length; i++)
entries[i] = this.entryAt(i);
return entries;
}
});
}
Documentation of the class Hashtable
Methods:
get(key)
Returns the value associated to the specified key.
Parameters:
key: The key from which to retrieve the value.
put(key, value)
Associates the specified value to the specified key.
Parameters:
key: The key to which associate the value.
value: The value to associate to the key.
remove(key)
Removes the specified key, together with the value associated to it.
Parameters:
key: The key to remove.
clear()
Clears the whole hashtable, by removing all its entries.
indexOfKey(key)
Returns the index of the specified key, according to the order entries have been added.
Parameters:
key: The key of which to get the index.
indexOfValue(value)
Returns the index of the specified value, according to the order entries have been added.
Parameters:
value: The value of which to get the index.
Remarks:
Values are compared by identity.
entryAt(index)
Returns an object with a key and a value properties, representing the entry at the specified index.
Parameters:
index: The index of the entry to get.
containsKey(key)
Returns whether the hashtable contains the specified key.
Parameters:
key: The key to look for.
containsValue(value)
Returns whether the hashtable contains the specified value.
Parameters:
value: The value to look for.
forEach(iterator)
Iterates through all the entries in the hashtable, calling specified iterator.
Parameters:
iterator: A method with three parameters, key, value and index, where index represents the index of the entry according to the order it's been added.
Properties:
length (Read-only)
Gets the count of the entries in the hashtable.
keys (Read-only)
Gets an array of all the keys in the hashtable.
values (Read-only)
Gets an array of all the values in the hashtable.
entries (Read-only)
Gets an array of all the entries in the hashtable. They're represented the same as the method entryAt().
function HashTable() {
this.length = 0;
this.items = new Array();
for (var i = 0; i < arguments.length; i += 2) {
if (typeof (arguments[i + 1]) != 'undefined') {
this.items[arguments[i]] = arguments[i + 1];
this.length++;
}
}
this.removeItem = function (in_key) {
var tmp_previous;
if (typeof (this.items[in_key]) != 'undefined') {
this.length--;
var tmp_previous = this.items[in_key];
delete this.items[in_key];
}
return tmp_previous;
}
this.getItem = function (in_key) {
return this.items[in_key];
}
this.setItem = function (in_key, in_value) {
var tmp_previous;
if (typeof (in_value) != 'undefined') {
if (typeof (this.items[in_key]) == 'undefined') {
this.length++;
} else {
tmp_previous = this.items[in_key];
}
this.items[in_key] = in_value;
}
return tmp_previous;
}
this.hasItem = function (in_key) {
return typeof (this.items[in_key]) != 'undefined';
}
this.clear = function () {
for (var i in this.items) {
delete this.items[i];
}
this.length = 0;
}
}
https://gist.github.com/alexhawkins/f6329420f40e5cafa0a4
var HashTable = function() {
this._storage = [];
this._count = 0;
this._limit = 8;
}
HashTable.prototype.insert = function(key, value) {
// Create an index for our storage location by passing
// it through our hashing function
var index = this.hashFunc(key, this._limit);
// Retrieve the bucket at this particular index in
// our storage, if one exists
//[[ [k,v], [k,v], [k,v] ] , [ [k,v], [k,v] ] [ [k,v] ] ]
var bucket = this._storage[index]
// Does a bucket exist or do we get undefined
// when trying to retrieve said index?
if (!bucket) {
// Create the bucket
var bucket = [];
// Insert the bucket into our hashTable
this._storage[index] = bucket;
}
var override = false;
// Now iterate through our bucket to see if there are any conflicting
// key value pairs within our bucket. If there are any, override them.
for (var i = 0; i < bucket.length; i++) {
var tuple = bucket[i];
if (tuple[0] === key) {
// Override value stored at this key
tuple[1] = value;
override = true;
}
}
if (!override) {
// Create a new tuple in our bucket.
// Note that this could either be the new empty bucket we created above
// or a bucket with other tupules with keys that are different than
// the key of the tuple we are inserting. These tupules are in the same
// bucket because their keys all equate to the same numeric index when
// passing through our hash function.
bucket.push([key, value]);
this._count++
// Now that we've added our new key/val pair to our storage
// let's check to see if we need to resize our storage
if (this._count > this._limit * 0.75) {
this.resize(this._limit * 2);
}
}
return this;
};
HashTable.prototype.remove = function(key) {
var index = this.hashFunc(key, this._limit);
var bucket = this._storage[index];
if (!bucket) {
return null;
}
// Iterate over the bucket
for (var i = 0; i < bucket.length; i++) {
var tuple = bucket[i];
// Check to see if key is inside bucket
if (tuple[0] === key) {
// If it is, get rid of this tuple
bucket.splice(i, 1);
this._count--;
if (this._count < this._limit * 0.25) {
this._resize(this._limit / 2);
}
return tuple[1];
}
}
};
HashTable.prototype.retrieve = function(key) {
var index = this.hashFunc(key, this._limit);
var bucket = this._storage[index];
if (!bucket) {
return null;
}
for (var i = 0; i < bucket.length; i++) {
var tuple = bucket[i];
if (tuple[0] === key) {
return tuple[1];
}
}
return null;
};
HashTable.prototype.hashFunc = function(str, max) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
var letter = str[i];
hash = (hash << 5) + letter.charCodeAt(0);
hash = (hash & hash) % max;
}
return hash;
};
HashTable.prototype.resize = function(newLimit) {
var oldStorage = this._storage;
this._limit = newLimit;
this._count = 0;
this._storage = [];
oldStorage.forEach(function(bucket) {
if (!bucket) {
return;
}
for (var i = 0; i < bucket.length; i++) {
var tuple = bucket[i];
this.insert(tuple[0], tuple[1]);
}
}.bind(this));
};
HashTable.prototype.retrieveAll = function() {
console.log(this._storage);
//console.log(this._limit);
};
/******************************TESTS*******************************/
var hashT = new HashTable();
hashT.insert('Alex Hawkins', '510-599-1930');
//hashT.retrieve();
//[ , , , [ [ 'Alex Hawkins', '510-599-1930' ] ] ]
hashT.insert('Boo Radley', '520-589-1970');
//hashT.retrieve();
//[ , [ [ 'Boo Radley', '520-589-1970' ] ], , [ [ 'Alex Hawkins', '510-599-1930' ] ] ]
hashT.insert('Vance Carter', '120-589-1970').insert('Rick Mires', '520-589-1970').insert('Tom Bradey', '520-589-1970').insert('Biff Tanin', '520-589-1970');
//hashT.retrieveAll();
/*
[ ,
[ [ 'Boo Radley', '520-589-1970' ],
[ 'Tom Bradey', '520-589-1970' ] ],
,
[ [ 'Alex Hawkins', '510-599-1930' ],
[ 'Rick Mires', '520-589-1970' ] ],
,
,
[ [ 'Biff Tanin', '520-589-1970' ] ] ]
*/
// Override example (Phone Number Change)
//
hashT.insert('Rick Mires', '650-589-1970').insert('Tom Bradey', '818-589-1970').insert('Biff Tanin', '987-589-1970');
//hashT.retrieveAll();
/*
[ ,
[ [ 'Boo Radley', '520-589-1970' ],
[ 'Tom Bradey', '818-589-1970' ] ],
,
[ [ 'Alex Hawkins', '510-599-1930' ],
[ 'Rick Mires', '650-589-1970' ] ],
,
,
[ [ 'Biff Tanin', '987-589-1970' ] ] ]
*/
hashT.remove('Rick Mires');
hashT.remove('Tom Bradey');
//hashT.retrieveAll();
/*
[ ,
[ [ 'Boo Radley', '520-589-1970' ] ],
,
[ [ 'Alex Hawkins', '510-599-1930' ] ],
,
,
[ [ 'Biff Tanin', '987-589-1970' ] ] ]
*/
hashT.insert('Dick Mires', '650-589-1970').insert('Lam James', '818-589-1970').insert('Ricky Ticky Tavi', '987-589-1970');
hashT.retrieveAll();
/* NOTICE HOW THE HASH TABLE HAS NOW DOUBLED IN SIZE UPON REACHING 75% CAPACITY, i.e. 6/8. It is now size 16.
[,
,
[ [ 'Vance Carter', '120-589-1970' ] ],
[ [ 'Alex Hawkins', '510-599-1930' ],
[ 'Dick Mires', '650-589-1970' ],
[ 'Lam James', '818-589-1970' ] ],
,
,
,
,
,
[ [ 'Boo Radley', '520-589-1970' ],
[ 'Ricky Ticky Tavi', '987-589-1970' ] ],
,
,
,
,
[ [ 'Biff Tanin', '987-589-1970' ] ] ]
*/
console.log(hashT.retrieve('Lam James')); // 818-589-1970
console.log(hashT.retrieve('Dick Mires')); // 650-589-1970
console.log(hashT.retrieve('Ricky Ticky Tavi')); //987-589-1970
console.log(hashT.retrieve('Alex Hawkins')); // 510-599-1930
console.log(hashT.retrieve('Lebron James')); // null
You can create one using like the following:
var dictionary = { Name:"Some Programmer", Age:24, Job:"Writing Programs" };
// Iterate over using keys
for (var key in dictionary) {
console.log("Key: " + key + " , " + "Value: "+ dictionary[key]);
}
// Access a key using object notation:
console.log("Her name is: " + dictionary.Name)