// food object
var food1 = {
// returns food ingredients.
getIngredients: function() {
let ingredients = ["pepper", "salt", "crayfish"];
return ingredients;
}
}
var food2 = {
// returns food ingredients.
getIngredients: function() {
let ingredients = ["pepper", "maggi", "oil"];
return ingredients;
}
}
var food3 = {
// returns food ingredients.
getIngredients: function() {
let ingredients = ["inzu", "ogiri", "crayfish"];
return ingredients;
}
}
var foods = [food1, food2, food3];
var index = 2;
var getMyFoodIngredients = (function(){
let foodIngredients = foods[index].getIngredients();
return (index)=>{
foodIngredients = foods[index].getIngredients();
return foodIngredients;}
})();
function removeIngredient(){
let foodIngredients = getMyFoodIngredients(index);
foodIngredients.pop();
console.log(foodIngredients)
}
for (var x = 0; x < 3; x++)
removeIngredient();
The problem with this approach is that since am using an immediately invoking function(IIFE) the foodIngredients is been initialized once but i want the index of foods[] to be dynamically initialized and also form a closure
So how do i pass an argument to dynamically change the foods[] ingredient
Related
I'm totally confused as to why 'cb' is not a function in my case.
Basically I have a 'Tree' constructor
this.value = value;
this.children = [];
};
Tree.prototype.addChild = function (value){
var newInstance = new Tree(value);
this.children.push(newInstance);
}
Tree.prototype.map = function(cb){
var copyTree = new Tree(this.value); //1
copyTree.value = cb(copyTree.value);
for (var i = 0; i < this.children.length; i++){ // i = 0; 2 i = 0's value is 2
copyTree.addChild(new Tree.prototype.map(cb(this.children[i].value)))
}
return copyTree;
}
and then in the console I've passed in
var root1 = new Tree(1)
var branch1 = root1.addChild(2);
var branch2 = root1.addChild(3);
Now every time I invoke
var newTree = root1.map(function (value) {
return value * 2 })
I keep getting this error.
VM1769 Script snippet %231:13 Uncaught TypeError: cb is not a function
at new Tree.map (VM1769 Script snippet %231:13)
at Tree.map (VM1769 Script snippet %231:19)
at <anonymous>:1:21
I know that my mapping method might not be right but just the fact that 'cb' is not a function confuses me, I'm passing in an anonymous function on the .map call but.. 'cb' is not a function? Why is that?
Inside .map, you have an array of trees to copy inside this.children. Since the array is composed of trees, those trees already have a .map method which you can call to create a copy of that tree. Change
copyTree.addChild(new Tree.prototype.map(cb(this.children[i].value)))
to
copyTree.addChild(this.children[i].map(cb))
function Tree(value) {
this.value = value;
this.children = [];
};
Tree.prototype.addChild = function(value) {
var newInstance = new Tree(value);
this.children.push(newInstance);
}
Tree.prototype.map = function(cb) {
var copyTree = new Tree(this.value);
copyTree.value = cb(copyTree.value);
for (var i = 0; i < this.children.length; i++) {
copyTree.addChild(this.children[i].map(cb))
}
return copyTree;
}
var root1 = new Tree(1)
var branch1 = root1.addChild(2);
var branch2 = root1.addChild(3);
var newTree = root1.map(function(value) {
return value * 2
})
console.log(newTree);
More readably, using modern syntax:
class Tree {
constructor(value) {
this.value = value;
this.children = [];
}
addChild(value) {
const newInstance = new Tree(value);
this.children.push(newInstance);
}
map(cb) {
const copyTree = new Tree(this.value);
copyTree.value = cb(copyTree.value);
for (const child of this.children) {
copyTree.addChild(child.map(cb))
}
return copyTree;
}
}
const root1 = new Tree(1)
const branch1 = root1.addChild(2);
const branch2 = root1.addChild(3);
const newTree = root1.map(value => value * 2);
console.log(newTree);
I am attempting to create a simple program for practice that has a Store constructor which takes in an inventoryList array, an InventoryItem constructor that creates an object of each item to be stored within the inventoryList array. I want to add a method to the InventoryItem list that will take a number and add it to each item within the list. Below is my code:
var Store = function(inventory){
this.inventory = inventory;
}
var InventoryItem = function(cost, color, size){
this.cost = cost;
this.color = color;
this.size = size;
}
//create each inventory item as an object
var lamp = new InventoryItem(40.00, 'blue', 'small');
var throwPillow = new InventoryItem(25.00, 'yellow', 'medium');
var sconce = new InventoryItem( 18.00, 'gold', 'large');
var candles = new InventoryItem(10.00, 'white', 'small');
var curtains = new InventoryItem(30.00, 'purple', 'large');
//store inventory items into an inventory object
var inventorylist = [lamp, throwPillow, sconce, candles, curtains];
// add number of items to each item
InventoryItem.prototype.howMany = function(num){
function addCount(inventorylist){
for(var i = 0; i < inventorylist.length; i++){
inventorylist[i].howMany = num;
}
}
}
//store inventory within a store
var deannaStore = new Store(inventorylist);
var dionStore = new Store(inventorylist);
var mikeStore = new Store(inventorylist);
I am running into an issue when I attempt add a number to an item within the list
example: dionStore.howMany(15)
this gives me the error: Uncaught TypeError: dionStore.howMany is not a function
Any help would be greatly appreciated preferably with a detailed explanation of why this doesn't work.
The problem is that the method howMany is defined for InventoryItem objects, but you try to call it to dionStore object which is a Store.
Can you please describe what you want to achieve?
EDIT1 :
Maybe add the howMany method to Store, like Lashane mentions, which will create a quantity property to each InvetoryItem in its array
Store.prototype.howMany = function(num){
function addCount(inventorylist){
for(var i = 0; i < inventorylist.length; i++){
inventorylist[i].quantity = num;
}
}
}
EDIT2 :
In this case you will need a method in InventoryItem to set the quantity and another in Store to return the total quantity
Store.prototype.howMany = function(){
var totalQuantity = 0;
for(var i = 0; i < inventorylist.length; i++){
var item = inventorylist[i];
if (item.hasOwnProperty('quantity')) {
totalQuantity += item.quantity;
}
}
return totalQuantity;
}
InventoryItem.prototype.addQuantity = function(quantity) {
if (this.hasOwnProperty('quantity')) {
this.quantity += quantity;
} else {
this.quantity = quantity;
}
}
var Store = function(inventory) {
this.inventory = inventory;
}
Store.prototype.howMany = function() {
var totalQuantity = 0;
for (var i = 0; i < inventorylist.length; i++) {
var item = inventorylist[i];
if (item.hasOwnProperty('quantity')) {
totalQuantity += item.quantity;
}
}
return totalQuantity;
}
var InventoryItem = function(cost, color, size) {
this.cost = cost;
this.color = color;
this.size = size;
}
InventoryItem.prototype.addQuantity = function(qunatity) {
if (this.hasOwnProperty('quantity')) {
this.quantity += qunatity;
} else {
this.quantity = qunatity;
}
}
//create each inventory item as an object
var lamp = new InventoryItem(40.00, 'blue', 'small');
var throwPillow = new InventoryItem(25.00, 'yellow', 'medium');
var sconce = new InventoryItem(18.00, 'gold', 'large');
var candles = new InventoryItem(10.00, 'white', 'small');
var curtains = new InventoryItem(30.00, 'purple', 'large');
//store inventory items into an inventory object
var inventorylist = [lamp, throwPillow, sconce, candles, curtains];
lamp.addQuantity(1);
throwPillow.addQuantity(2);
sconce.addQuantity(3);
candles.addQuantity(4);
curtains.addQuantity(5);
lamp.addQuantity(1);
//store inventory within a store
var deannaStore = new Store(inventorylist);
var dionStore = new Store(inventorylist);
var mikeStore = new Store(inventorylist);
document.getElementById('output').innerHTML = 'dionStore.howMany() = ' + dionStore.howMany();
<div id="output"></div>
Your prototype defines a function and does nothing. And it is on the wrong prototype. Are you looking for this?
Store.prototype.howMany = function(num){
for(var i = 0; i < this.inventory.length; i++){
this.inventory[i].howMany = num;
}
}
function test(results) {
//Populate the ComboBox with unique values
var Gov;
var values = [];
var features = results.features;
var og;
for (i = 0; i < features.length; i++) {
var aGOV = {
"GovName": features[i].attributes.ENG_NAME,
"GovNO": features[i].attributes.GOV_NO,
"Shape": features[i].geometry
}
og = new Option(features[i].attributes.ENG_NAME, aGOV);
var cbx = document.getElementById("cbxGov");
cbx.options.add(og);
}
}
function gov_selection_change()
{
var cbx = document.getElementById("cbxGov");
var itm = cbx.options[cbx.selectedIndex].value.hasOwnProperty("Shape");
}
html code
<select id="cbxGov" onchange="gov_selection_change()">
My problem is i m not able to access property of aGOV in my gov_selection_change() function, it shows it has no such property, itm is false.
The value property of an HTMLOptionElement always returns a DOMString (a.k.a. text), not an object.
So you have to save what you want to access in a lookup dictionary and then use the returned value as a lookup key.
var lookupDictionary = {};
function test(results) {
var lookupKey,
og;
//...
// don´t get the element in the loop
var cbx = document.getElementById("cbxGov");
//...
for (i = 0; i < features.length; i++) {
lookupKey = features[i].attributes.GOV_NO;
lookupDictionary[lookupKey] = {
"GovName": features[i].attributes.ENG_NAME,
"GovNO": features[i].attributes.GOV_NO,
"Shape": features[i].geometry
}
og = new Option(features[i].attributes.ENG_NAME, lookupKey );
cbx.options.add( og );
}
}
function gov_selection_change() {
var cbx = document.getElementById("cbxGov");
var key = cbx.options[cbx.selectedIndex].value;
var itm = lookupDictionary[key].hasOwnProperty("Shape");
}
The variable aGOV is only available in the context of your result() function. If you want to use it from a different function declare it as a global variable.
Example:
var aGOV;
function result()
{
// initialize aGOV
}
function gov_selection_change()
{
// now you can access the aGOV variable
}
I am trying to pass product into the find() function that contains a .toArray() anonymous function containing both error and array. Unfortunately this entire find() function runs within an iteration and only the first value goes in. How do I pass product to the callbacks?
var find = function(product,callbacks){
foos.find({
"foo": product.bars,
}).toArray(function (error, array) {
if(error){
callbacks.error(product,error);
} else if (array.length == 0) {
callbacks.none(product);
} else {
callbacks.exists(product);
}
});
}
Before this function i was processing products with forEach() then had this run in a callback within that. This was big trouble. Processed products with a regular for and now it works.
Old code
var products = function(data,callback){
products.forEach(function(product){
insert.product_id = product.id;
var variants = product.variants;
variants.forEach(function(variant){
insert.sku = variant.sku;
insert.variant_id = variant.id;
return callback(insert);
});
});
}
New code
var products = function(data){
var insert = [];
var products = data.products;
for(var pKey in products){
var product = products[pKey];
var variants = product.variants;
var set = {}
set.product_id = product.id;
for(var vKey in variants){
var variant = variants[vKey];
set.sku = variant.sku;
set.variant_id = variant.id;
insert.push(set);
}
}
return insert;
}
may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);