javascript object arrays - javascript

I need to migrate a code in java to javascript.
In java, I am maintaining a hashmap with key = string and value = arraylist of objects
I need to implement the same in javascript:
this.hashMap = new Hash();
this.hashMapArrayList =[];
...
var hashMapDataSet = new HashMapDataSet(id1,name1,type1);
this.hashMapArrayList[0] = hashMapDataSet;
...
this.hashMap.set(fileName1, this.hashMapArrayList);
var hashMapDataSet1= new HashMapDataSet(id2,name2,type2);
this.hashMapArrayList[0] = hashMapDataSet1;
this.hashMap.set(fileName2, this.hashMapArrayList);
But when I try to get the properties for a specified key
this.hashMap.get(fileName1).getId()
I get the value= id2 which is the last id that was set for HashMapDataSet object.
I have tried to mimic getters and setters in javascript as specified in the following link:
http://javascript.crockford.com/private.html
Here is the HashMapDataSet class
function HashMapDataSet(pId, pName, pType) {
var id = pId;
var name = pName;
var type = pType;
function getId1() {
return id;
}
function setId1(mId) {
id = mId;
}
....
this.getId = function () {
return getId1();
};
this.setId = function (id) {
setId1(id);
};
...
}
where getId1, setId1 are private methods and
getId, setId are priviledged methods
I am new to javascript, so I am unable to correlate java object with javascript. Kindly help.

I'm not quite sure what you're trying to do there, but in javascript you don't need all this java wiring, because the language has built-in maps and lists. Your snippet can look like this in js
this.hashMap = {};
this.hashMapArrayList =[];
...
this.hashMapArrayList.push({id: id1, name: name1, type: type1});
...
this.hashMap.fileName1 = this.hashMapArrayList;
this.hashMapArrayList.push({id: id2, name: name2, type: type2 });
this.hashMap.fileName2 = this.hashMapArrayList;

The javascript-closure-loop problem is very common.
I would take a lot to: http://www.javascriptkata.com/2007/04/11/a-common-problem-with-the-powerful-javascript-closures/
Regards.

for the class you needn't private functions, you can use directly privileged functions:
function HashMapDataSet(pId, pName, pType)
{
var id = pId;
var name = pName;
var type = pType;
this.getId = function ()
{
return id;
};
this.setId = function (pId)
{
id = pId;
}
}

Related

Use a function to add and one to remove an object from an array

I haven't be able to use the push() method to use the new Food constructor to create new items in my pantry array. I need a function to call that will add objects to the array, and I would like for the id value to be calculated based on the current length of the array.
I have tried to create functions like
groceries = function ()
{
pantry.push(new Food)};
var pantry =
[
egg = new Food (1, "Egg", ...)
...
...
];
function Food (id, name,...)
{
this.id = id;
this.name = name;
...
};
this.inquiry = function() {
return '\n' + this.name +
'\n' +
};
I can go to the browser and pantry.push(chicken = new Food(... arguments...); but I'm coming up short on knowledge in how to construct a function that would make the process cleaner. I'm not sure if this is just how it is. Maybe I can't do this with a constructor in mind. I'm very new.
I expect there is a way to type in a function that will use my constructor to format new variables and then push them to the end of my pre made variable pantry. I'd like to be able to use this function in the browser.
so far i'm getting errors like function not defined or syntax error.
I think you mean class instead of function. new can only use for class. Like below.
class Food {
constructor(id, name) {
this.id = id;
this.name = name;
}
inquiry() {
return '\n' + this.name + '\n';
}
}
var pantry = [ new Food(1, "Egg") ];
console.log(pantry);
console.log(pantry[0].inquiry());
Here is yet another solution you could use
class FoodStore{
constructor() {
this.data = [];
}
add(name){
this.data.push({id: this.data.length,name});
}
toList(){
return this.data;
}
}
var store = new FoodStore();
store.add("test");
//inquiry
console.log(store.toList()[0].name);
// All items
console.log(store.toList());

JavaScript: use an object returned by function without object of object

I am new in JavaScript/jQuery. Wondering if there is any better way to return an object by a function.
//this is the Object creator.
function makeNewPlayer(name, score) {
var player = {};
player.name = name;
player.score = score;
return player;
};
This is how I use the function.
var player_info = makeNewPlayer('Bob' ,100);
However, when I use the object, I need to call it like this:
player_info.player.name
player_info.player.score
It looks stupid, any way to use the object directly like this?
player_info.name
player_info.score
edit:
As I don't know how many object will be created by the function.
Let say there is a for loop to make score_1, score_2 etc.
function makeNewPlayer(name, score) {
var player = {};
player.name = name;
for(i=0, i<number_of_score, i++){
eval("player.score_" + i) = score[i];
};
return player;
};
You can use destructing assignment to declare global or locally scoped variables
//this is the Object creator.
function makeNewPlayer(name, score) {
var player = {};
player.name = name
player.score = score
return player;
};
var player_info = makeNewPlayer("Bob", 100);
{
let {name: _name, score} = player_info;
// do stuff with `_name`, `score`
console.log(_name, score);
}
Use new.
I copied some text from my blog that happened to resolve your doubts:
A constructor is a special function used for creating an object:
Example:
function StarkIndustries(name, birth) {
this.name = name;
this.birth = birth;
}
var iron1 = new StarkIndustries('iron01', 2017);
var iron2 = new StarkIndustries('iron02', 2017);
alert(iron1.name);
alert(iron2.name);
Result:
iron01
iron02
By adding new before a function, the function is turned into a
constructor that constructs an object.
But it is dangerous to call a function designed as a constructor
without new, because it will modify the global object window. So sanity check inside the constructor is required:
if (!(this instanceof StarkIndustries)) {
warn("StarkIndustries is a constructor and should be called with `new`");
}
Back to your code, it should be:
function makeNewPlayer(name, score) {
this.name = name
this.score = score
};
var iron1 = new makeNewPlayer('iron01', 2017);
Aside for the fact that "Bob" should be in quotes, it's working fine for me.
var player_info = makeNewPlayer('Bob', 100);
and then I am able to access it just fine like this:
player_info.name
player_info.score
function makeNewPlayer(name, score) {
return {name, score};
};
let players = [];
// in for loop -- sample code only, you need to supply name & score
{
players.push(makeNewPlayer(name, score));
}
You can use a temporary constructor function inside of your function :
function makeNewPlayer(name, score){
const Player = function(name, score){
this.name = name;
this.score = score;
};
return new Player(name, score);
}
You can also use an external function instead of a nested one.
With no change to your function, i am able to get the output the way you want it
player_info.name
player_info.score
Check out the snippet below
//this is the Object creator.
function makeNewPlayer(name, score) {
var player = {};
player.name = name
player.score = score
return player;
};
var player_info = makeNewPlayer("Bob", 100);
console.log(player_info.name);
console.log(player_info.score);

Class inside a namespace

I'd like my code to look something like this, but I don't know how to make that happen.
var employee = namespace.employee(2); // return object
var employeeName = namespace.employee(2).name; // return string
var name = employee.name;
I was thinking of creating a namespace like this
var namespace = (function(){
})();
And then putting like classes inside it, I just don't quite know where to start.
This is all you need to implement that behaviour:
var namespace = {};
namespace.employee = function (num) {
return { name: num };
};
The function employee on the object namespace which returns an object containing the key name.
Assuming you want something like a repository of employees and the num tells it which employee to return:
var namespace = {};
var employees = [{ name: 'Joe' }, ...];
namespace.employee = function (num) {
return employees[num];
};
Assuming you want the employees repository to not be globally accessible:
var namespace = {};
namespace.employee = (function () {
var employees = [{ name: 'Joe' }, ...];
return function (num) {
return employees[num];
};
})();

javascript: define variable to object like a magic setter

I am trying to set some variable to an object. But i want it to be set like the code below
is there a way to set a variable like this?
myObject = {};
myObject.save = function (var) {
console.log(var);
}
myObject.users.save(); // must output 'users';
myObject.fruits.save(); // output fruit;
the save method is just an example method. it means that i need to chain a method on the variable string.
i trying to achieve something like that.
any ideas how to achieve that?
thanks
You can create a List class for your users and fruits lists, and provide regular list methods like add, remove, size and etc. to make it actually like a list class, and define your save method as a prototype method:
var List = (function(){
function List(listType){
this.listType = listType;
this._list = [];
}
List.prototype.add = function(item){
this._list.push(item);
};
List.prototype.size = function(item){
return this._list.length;
};
List.prototype.save = function(item){
console.log(this.listType);
};
return List;
})();
then you can use it in your object like:
var myObject = {};
myObject.users = new List("users");
myObject.fruits = new List("fruits");
now you can actually call those two lines of code:
myObject.users.save(); // output 'users';
myObject.fruits.save(); // output 'fruits';
and you can also define a save method for myObject and actually call the lists save method:
myObject.save = function(listType){
if(myObject[listType] instanceof List){
myObject[listType].save();
}
else{
console.log("there is no such a list named : " + listType);
}
};
and call it like:
myObject.save("users");
myObject.save("fruits");
You can do like
var obj = {
users: {
save: function () {
console.log('Users');
}
},
fruits: {
save: function () {
console.log('Fruits');
}
},
}
(or)
var obj = {};
obj.users = {};
obj.users.save = function () {
console.log('Users');
};
obj.fruits = {};
obj.fruits.save = function () {
console.log('Fruits');
};

Casting an object to a custom class

I'm developing a HTML 5 application.
In Javascript I have defined a custom class and a HashTable implementation:
function Card(newId, newName, newDescription)
{
this.id = newId;
this.name = newName;
this.description = newDescription;
}
function HashTable()
{
var hashTableItems = {};
this.SetItem = function(key, value)
{
hashTableItems[key] = value;
}
this.GetItem = function(key)
{
return hashTableItems[key];
}
}
I use HashTable to add Card's objects. I use this code to add cards:
...
var card = new Card(id, name, description);
$.viacognitaspace.cards.SetItem(id, card);
...
My problem is when I call HashTable.GetItem and I don't know how to cast object returned to Card class.
var cardObject = $.viacognitaspace.cards.GetItem(cardNumber);
Here, cardObject is undefined.
If I do this:
$('#cardName').text(cardObject.name);
I get an error.
How can I fix this?
Try modifying your code to the following:
$.viacognitaspace = {} /* define namespace if not already defined... */
var card = new Card(id, name, description);
/* the "new" keyword creats an instance of your HashTable function
which allows you to reference and modify it later on... */
$.viacognitaspace.cards = new HashTable();
$.viacognitaspace.cards.SetItem(id, card);
You also need to create an instance of the HashTable function.
Example:
http://jsfiddle.net/3BWpM/

Categories