Updating an array returned by a function - javascript

I've been trying to implement some card game using Javascript. In the snippet below, I simply want to pull two cards from the top of the deck and give it to the player (simplified logic below)
function deck() {
var faceCards = [['jack', 11],['queen', 12],['king', 13]];
return faceCards;
}
function removeCard() {
var singleCard = deck().pop();
var faceValue = singleCard[0];
return faceValue;
}
var cardPair = [removeCard(),removeCard()];
console.log(cardPair);
However the faceCards array is still the same even after popping off its cards which means that the next card will be the same as well as seen in cardPair array.
I need to mirror the effects I used inside of the
removeCard() function to reflect back in the deck() function.
I suppose I could either create the faceCards array in the global scope or use 'this' in some way (which I don't really want as I'm not much familiar with it). How can I update one function from inside another function? Thank you very much for reading this.

Your error is here:
var singleCard = deck().pop()
The call to deck() creates a new array of cards every time it's called, and doesn't repeatedly return the same array.
If you don't want to go full OO yet, consider at least passing the deck as a parameter to the removeCard() function, i.e.
function removeCard(deck) {
var singleCard = deck.pop();
var faceValue = singleCard[0];
return faceValue;
}
var deck = newDeck();
var pair = [ removeCard(deck), removeCard(deck) ];
but ultimately you should longer term be going for a full OO solution, where your usage might then become:
var deck = new Deck();
var pair = [ deck.takeCard(), deck.takeCard() ];
implementation of this is out of scope of this particular question.

You're creating a new array every time you run deck(). Try saving the deck in an array and running pop on this:
function deck() {
var faceCards = [['jack', 11],['queen', 12],['king', 13]];
return faceCards;
}
function removeCard(fromDeck) {
var singleCard = fromDeck.pop();
var faceValue = singleCard[0];
return faceValue;
}
var thisDeck = deck();
var cardPair = [removeCard(thisDeck),removeCard(thisDeck)];
console.log(cardPair);

Related

Pass variables from function to router(Same page)

I have a question regarding Node.js that I started using recently and I don't have much dexterity yet.
So, I have a function inside the pages.js file and I need some values ​​to be passed to HTML in the same way that was done with "arrayOfCookies", (passing to the router that is also in pages.js). However what I understood is that the function needs to return next () for the page to be loaded. Is there any way to pass these values ​​(7 variables) to the router.get in a similar way to what I have already done with cookies? My goal is to display those in my HTML. I appreciate any help, my code is below - Im not going to put my function here cause i guess its not relevant to answer my question.
router.get('/userPage',beforeReq,authFunct,(req,res) =>{
var arrayOfCookies = req.cookies['myEmail'];
///exercises1,exercises2,exercises3,exercises4,exercises5,exercises6,exercises7 are the variables that i need to pass from my function to the line below. They are all arrays
res.render('userPage', {name: arrayOfCookies})
And this is just a part of the function that I want to pass the values ​​of
function beforeReq(req,res,next){
var allExercises = []
var exercises1 = []
var exercises2 = []
var exercises3 = []
var exercises4 = []
var exercises5 = []
var exercises6 = []
var exercises7 = []
return next()
}

Javascript Module Pattern accessing updated parameter value

I've tried to search for an answer to my question, but I'm starting to think that, given the lack of results, I'm obviously not expressing the question properly. With that in mind, apologies if the title of this post is misleading, I am still very much learning.
I have a simplified version of my code below
var testData = ['a', 'b']
var addReceiver = (function () {
dataReceiver = function (dataInput) {
t = this
t.data = dataInput;
console.log(t.data);
t.interval = setInterval(function () {
t.update();
}, 1000);
t.stopUpdate = function () { clearInterval(t.interval); };
t.update = function () {
//t.data = dataInput;
console.log(t.data);
};
};
})()
var testLogger = new dataReceiver(testData);
</script>
The behaviour that I wish to emulate is when I type into the console
testData = ['c','d','e']
for testLogger to log the array ['c','d','e'] every second rather than ['a','b'].
I could change
t.data = dataInput to t.data = testData
to achieve this, but that would obviously be pointless, or else every new instance I created of dataReceiver would have a reference to the same data input.
So, my question is, how would I need to change the code to provide the testLogger vairable (or any instance of dataReceiver) access to a variable outside of its local scope?
Use the object that you have created instead of accessing the global variable,
var testLogger = new dataReceiver(testData);
testLogger.data = [1,2,3,4];
Now you will be able to print the newly injected data. I mean the setInterval will print the updated value.

Create variable to JavaScript array from another function?

I have a function that create and store an array for all the p elements:
function dummyArray(){
var $dummy= $('p');
var dummy= [];
i = 0;
$dummy.each(function()
{
dummy[i++] =$(this).html();
});
return dummy;
}
Now, in order to reuse the array in another function, I can use dummyArray() and dummyArray()[0] to access the individual data.
function initAll(){
//dummyArray();
//dummyArray()[0];
}
However I want to store it inside a variable like below but it gives me error.
function initAll(){
var allArray = dummyArray();//error
}
Is there a way to store it inside a variable or is there a better way of doing this?
After cleaning up my code I noticed that using var allArray = dummyArray(); does work, the error was generated from something else. cheers~
Edited:
The error I found out was the function name cannot be the same as the new variable name declared even though the () aren't there.
var dummyArray = dummyArray();//error
var allArray = dummyArray();//works

javascript function to save data in global variables

I have problems to make this function (addMe) to save the data from img and span from div childBox in two global arrays?
I think something is wrong in the function but can't see what.
This is my code.
Global var: //before function init
var imgSrclist = [];
var imgSpanlist = [];
Function:
function addMe(obj) {
var el = document.getElementById(obj.getAttribute('data-img'));
var parent = el.parentNode.getElementsByClassName('childBox')[0],
imgSRC = parent.getElementsByName('img')[0].src,
spanTXT = parent.getElementsByTagName('span')[0].innerHTML;
if (obj.checked) {
imgSpanlist[el.id].imgSrc.push(imgSRC);
imgSrclist[el.id].imgSpan.push(spanTXT);
} else {
var imgIx = imgSrclist[el.id].imgSrc.indexOf(imgSRC),
spanIx = imgSpanlist[el.id].imgSpan.indexOf(spanTXT);
imgSrclist[el.id].imgSrc.splice(imgIx);
imgSpanlist[el.id].imgSpan.splice(spanIx);
}
}
The data should be saved on global variabels because it will be used later in a new window when you push a button. The script code for the new windows starts with this:
var imgSrclist = window.opener.imgSrclist;
var imgSpanlist = window.opener.imgSpanlist;
EDIT: The code is now updated, so the arrays is declared. But the problem is that the imgsrc and span text dosen´t comes to the new window. are they saved in the array at all?
Two things I want to mention is;
var imgSrclist;
var imgSpanlist;
should declare as an array and
function init() {
imgSrc=[]; //Empty array
imgSpan=[]; //Empty array
}
why they are declare as an array as you are not using these as an array.
I have updated two above changes, here is your code.

Functional object basics. How to go beyond simple containers?

On the upside I'm kinda bright, on the downside I'm wracked with ADD. If I have a simple example, that fits with what I already understand, I get it. I hope someone here can help me get it.
I've got a page that, on an interval, polls a server, processes the data, stores it in an object, and displays it in a div. It is using global variables, and outputing to a div defined in my html. I have to get it into an object so I can create multiple instances, pointed at different servers, and managing their data seperately.
My code is basically structured like this...
HTML...
<div id="server_output" class="data_div"></div>
JavaScript...
// globals
var server_url = "http://some.net/address?client=Some+Client";
var data = new Object();
var since_record_id;
var interval_id;
// window onload
window.onload(){
getRecent();
interval_id = setInterval(function(){
pollForNew();
}, 300000);
}
function getRecent(){
var url = server_url + '&recent=20';
// do stuff that relies on globals
// and literal reference to "server_output" div.
}
function pollForNew(){
var url = server_url + '&since_record_id=' + since_record_id;
// again dealing with globals and "server_output".
}
How would I go about formatting that into an object with the globals defined as attributes, and member functions(?) Preferably one that builds its own output div on creation, and returns a reference to it. So I could do something like...
dataOne = new MyDataDiv('http://address/?client');
dataOne.style.left = "30px";
dataTwo = new MyDataDiv('http://different/?client');
dataTwo.style.left = "500px";
My code is actually much more convoluted than this, but I think if I could understand this, I could apply it to what I've already got. If there is anything I've asked for that just isn't possible please tell me. I intend to figure this out, and will. Just typing out the question has helped my ADD addled mind get a better handle on what I'm actually trying to do.
As always... Any help is help.
Thanks
Skip
UPDATE:
I've already got this...
$("body").prepend("<div>text</div>");
this.test = document.body.firstChild;
this.test.style.backgroundColor = "blue";
That's a div created in code, and a reference that can be returned. Stick it in a function, it works.
UPDATE AGAIN:
I've got draggable popups created and manipulated as objects with one prototype function. Here's the fiddle. That's my first fiddle! The popups are key to my project, and from what I've learned the data functionality will come easy.
This is pretty close:
// globals
var pairs = {
{ div : 'div1', url : 'http://some.net/address?client=Some+Client' } ,
{ div : 'div2', url : 'http://some.net/otheraddress?client=Some+Client' } ,
};
var since_record_id; //?? not sure what this is
var intervals = [];
// window onload
window.onload(){ // I don't think this is gonna work
for(var i; i<pairs.length; i++) {
getRecent(pairs[i]);
intervals.push(setInterval(function(){
pollForNew(map[i]);
}, 300000));
}
}
function getRecent(map){
var url = map.url + '&recent=20';
// do stuff here to retrieve the resource
var content = loadResoucrce(url); // must define this
var elt = document.getElementById(map.div);
elt.innerHTML = content;
}
function pollForNew(map){
var url = map.url + '&since_record_id=' + since_record_id;
var content = loadResoucrce(url); // returns an html fragment
var elt = document.getElementById(map.div);
elt.innerHTML = content;
}
and the html obviously needs two divs:
<div id='div1' class='data_div'></div>
<div id='div2' class='data_div'></div>
Your 'window.onload` - I don't think that's gonna work, but maybe you have it set up correctly and didn't want to bother putting in all the code.
About my suggested code - it defines an array in the global scope, an array of objects. Each object is a map, a dictionary if you like. These are the params for each div. It supplies the div id, and the url stub. If you have other params that vary according to div, put them in the map.
Then, call getRecent() once for each map object. Inside the function you can unwrap the map object and get at its parameters.
You also want to set up that interval within the loop, using the same parameterization. I myself would prefer to use setTimeout(), but that's just me.
You need to supply the loadResource() function that accepts a URL (string) and returns the HTML available at that URL.
This solves the problem of modularity, but it is not "an object" or class-based approach to the problem. I'm not sure why you'd want one with such a simple task. Here's a crack an an object that does what you want:
(function() {
var getRecent = function(url, div){
url = url + '&recent=20';
// do stuff here to retrieve the resource
var content = loadResoucrce(url); // must define this
var elt = document.getElementById(div);
elt.innerHTML = content;
}
var pollForNew = function(url, div){
url = url + '&since_record_id=' + since_record_id;
var content = loadResoucrce(url); // returns an html fragment
var elt = document.getElementById(div);
elt.innerHTML = content;
}
UpdatingDataDiv = function(map) {
if (! (this instanceof arguments.callee) ) {
var error = new Error("you must use new to instantiate this class");
error.source = "UpdatingDataDiv";
throw error;
}
this.url = map.url;
this.div = map.div;
this.interval = map.interval || 30000; // default 30s
var self = this;
getRecent(this.url, this.div);
this.intervalId = setInterval(function(){
pollForNew(self.url, self.div);
}, this.interval);
};
UpdatingDataDiv.prototype.cancel = function() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
})();
var d1= new UpdatingDataDiv('div1','http://some.net/address?client=Some+Client');
var d2= new UpdatingDataDiv('div2','http://some.net/otheraddress?client=Some+Client');
...
d1.cancel();
But there's not a lot you can do with d1 and d2. You can invoke cancel() to stop the updating. I guess you could add more functions to extend its capability.
OK, figured out what I needed. It's pretty straight forward.
First off disregard window.onload, the object is defined as a function and when you instantiate a new object it runs the function. Do your setup in the function.
Second, for global variables that you wish to make local to your object, simply define them as this.variable_name; within the object. Those variables are visible throughout the object, and its member functions.
Third, define your member functions as object.prototype.function = function(){};
Fourth, for my case, the object function should return this; This allows regular program flow to examine the variables of the object using dot notation.
This is the answer I was looking for. It takes my non-functional example code, and repackages it as an object...
function ServerObject(url){
// global to the object
this.server_url = url;
this.data = new Object();
this.since_record_id;
this.interval_id;
// do the onload functions
this.getRecent();
this.interval_id = setInterval(function(){
this.pollForNew();
}, 300000);
// do other stuff to setup the object
return this;
}
// define the getRecent function
ServerObject.prototype.getRecent = function(){
// do getRecent(); stuff
// reference object variables as this.variable;
}
// same for pollForNew();
ServerObject.prototype.pollForNew = function(){
// do pollForNew(); stuff here.
// reference object variables as this.variable;
}
Then in your program flow you do something like...
var server = new ServerObject("http://some.net/address");
server.variable = newValue; // access object variables
I mentioned the ADD in the first post. I'm smart enough to know how complex objects can be, and when I look for examples and explanations they expose certain layers of those complexities that cause my mind to just swim. It is difficult to drill down to the simple rules that get you started on the ground floor. What's the scope of 'this'? Sure I'll figure that out someday, but the simple truth is, you gotta reference 'this'.
Thanks
I wish I had more to offer.
Skip

Categories

Resources