Javascript: Getting the newest array - javascript

I've been thinking about how to display the newest array (because the array list would update from time to time.). I think there's a default function to it but I can't find it. Anyone knows it?
var bgImg = new Array();
bgImg[0] = "background.jpg";
bgImg[1] = "background2.jpg";
bgImg[2] = "background3.jpg";
bgImg[3] = "background4.jpg";

If you want the last element of the array,
>>> a = ['background1','background2'];
["background1", "background2"]
>>> b = a[a.length-1]
"background2"
You shouldn't need to manually assign indexes. Just do bgImg.push('background2.jpg'), and it will mutate the array for you. In your case the syntax would be...
var last = bgImg[bgImg.length-1]
If you want the newest then you need to make a variable and set it with whatever you update when you push the newest one, if it doesn't become the last one.

You could create a little object to handle this for you.
function creatImageState() {
var images = [];
return {
get latest() {
return images[images.length - 1];
},
set latest (value) {
images.push(value);
}
};
}
var s = creatImageState();
s.latest = "a.png";
s.latest = "b.png";
alert(s.latest);
IE doesn't support getters and setters so you probably need to use this.
function creatImageState() {
var images = [];
return {
getLatest : function() {
return images[images.length - 1]
},
setLatest : function(value) {
images.push(value);
}
};
}
var s = creatImageState();
s.setLatest("a.png");
s.setLatest("b.png");
alert(s.getLatest());

Related

Using function of an object after grabbing it from array

When I try to grab the object from the array, the type is undefined. Therefore I cannot use a method from the undefined object as it doesn't exist. I am relatively new to JavaScript and I have come straight from Java so the way of retrieving objects is kind of new to me. This is what I currently have.
var fleetAmount = 0;
var fleets = [];
function Fleet(number) {
this.number = number;
this.activities = [];
this.addActivity = function (activity) {
this.activities.push(activity);
};
fleets.push(this);
}
var getFleet = function(fleetNumber) {
return fleets[fleetAmount - fleetNumber];
}
This is where I try to grab the object and preform the function
const Fl = require(‘fleet.js’);
const fleet = Fl.getFleet(fleetNumber);
fleet.addActivity(activity);
I am also working in Node.js, which is how I am using the require method.
In combination with the answer from #audzzy I changed the getFleet() function so that it would be more efficient. I tested it out and it worked. This is what I used
function getFleet(fleetNumber) {
let result = fleets.filter(function (e) {
return e.number = fleetNumber;
})
return result[0];
}
Thanks for the help! I appreciate it.
you want to create a new fleet object and add it, not "this"..
adding "this" would cause a circular reference, where
this.fleets[i] = this (and all fleets would have the same value)
when calling get fleet, I would check that a fleet was returned from get fleet
in case amount is less than the number you send to getFleet (where according to what you posted: 1 returns the last, 2 returns second to last etc..)..
I hope this explanation makes sense.. anyways, this should work..
var fleets = [];
doStuff();
function doStuff(){
addFleet(1);
addFleet(2);
addFleet(7);
addFleet(3);
// should return null
let fleet1 = getFleetByNumber(5);
// should return the fleet with number 7, and not change the fleet with number 1
let fleet2 = getFleetByNumber(7);
if(fleet2){
fleet2.addActivity("activity");
}
console.log(`fleets: ${JSON.stringify(fleets)} \nfleet1: ${JSON.stringify(fleet1)} \nfleet2: ${JSON.stringify(fleet2)}`);
}
function addFleet(number) {
let fleet = { number: number,
activities: [] };
fleet.addActivity = function (activity) {
this.activities.push(activity);
};
fleets.push(fleet);
}
function getFleetByNumber(fleetNumber) {
return fleets.find(function (e) {
return e.number == fleetNumber;
});
}
function getFleet(fleetNumber) {
let result = null;
if(fleets.length - fleetNumber >= 0){
result = fleets[fleets.length - fleetNumber];
}
return result;
}

How to use a formatted string to access SUB properties in a JavaScript object?

For the sake of reusable code, I am trying to avoid having to hardcode literally thousands of complex objects by instead using strings like "foo.bar.sub" to access properties.
Now I have quickly worked out a naive algorithm for getting the value of a property, like so:
getValueForPath : function(path) {
var pathArray = path.split('.'),
modelCopy = this;
while (pathArray.length > 0) {
modelCopy = modelCopy[pathArray.shift()];
}
return modelCopy;
},
However this will only return the value of a property, not let me set the value of a property. So it is only one half of the problem. Ideally I need a way to, for a given path, return the property itself, which i'm not sure is possible in JavaScript(But i'm not a JavaScript expert), or I need a second function to set the property for a given path, and I have so far been unable to work this out.
Any thoughts?
If you don't want to use another function, you can use
getValueForPath("foo.bar").sub = something;
Alternatively,
setValueForPath: function(path, val) {
var pathArray = path.split('.'),
modelCopy = this;
while (pathArray.length > 1) {
modelCopy = modelCopy[pathArray.shift()];
}
return modelCopy[pathArray[0]] = val;
}
getValueForPath("foo.bar.sub", something);
Also consider unifying both functions:
accessValueForPath: function(path, val) {
var pathArray = path.split('.'),
modelCopy = this,
b = val!==void 0;
while (pathArray.length > b) {
modelCopy = modelCopy[pathArray.shift()];
}
return b ? modelCopy[pathArray[0]] = val : modelCopy;
}
accessValueForPath("foo.bar.sub"); // read
accessValueForPath("foo.bar.sub", something); // write

Accessing the value of an observable inside a plain JS array in Knockout JS?

Background
I have a plain JS array, initially empty. I later populate it with values. The values sent to it are numbers that are Knockout observables. Later, I want to compare those values to values in another, knockout observable array. My problem is that whenever I pass the index of the current item in my array loop, and pass that index value (a number!), the array returns a function. To get an idea, look at the JS that follows.
Note that my project and actual script is viewable on JSBin. Further, to view the problem in the console, you have to add assignments, then press 'sort'.
JSBin: http://jsbin.com/fehoq/177/edit]1
JS
//example script that follows actual script
var _this = this;
//initialize my array
this. lowest = [];
// I want to compare values in lowest to values in this array
this.scores = ko.observableArray();
// method that does comparison
this.myMethod = function(){
// initialize my helper, k
var k;
...
// loop through one array
ko.utils.arrayForEach(_this.scores(), function (score) {
// make sure my value is a number...
if (!isNaN(parseFloat(score()))) {
// this is important, I need to current index for comparison
k = _this.scores.indexOf(score);
console.log(k);
// this is where things break - it prints a function, not a value!
console.log(_this.lowest[k]);
// useless check, the value is a function, so they're always different
if (score()!=_this.lowest[k]){
// do stuff
}
}
}
}
Update
Putting the method I'm using, maybe someone will notice something I missed given that my syntax is correct(?).
this.mean = (function(scores,i) {
var m = 0;
var count = 0;
var k;
ko.utils.arrayForEach(_this.scores(), function(score) {
console.log([typeof score(), score()]);
if (!isNaN(parseFloat(score()))) {
console.log(i);
console.log(_this.lowest[i]);
if (score() != _this.lowest[i]) {
m += parseFloat(score());
count += 1;
}
}
});
if (count) {
m = m / count;
return m.toFixed(2);
} else {
return 'N/A';
}
});
}
Update 2
Just in case someone else wanders over here since my problem isn't solve still. The following code is how I set the value of lowest:
this.dropLowestScores = function() {
ko.utils.arrayForEach(_this.students(), function(student){
var comparator = function(a,b){
if(a()<b()){
return 1;
} else if(a() > b()){
return -1;
} else {
return 0;
}
};
var tmp = student.scores().slice(0);
tmp.sort(comparator);
student.lowest = ko.observableArray(tmp.splice((tmp.length-2),tmp.length-1));
});
};
Outstanding Questions, 5/9/2014
Jeremy's script runs but without the desired effects. For example, console.log(_this.lowest[k]) prints undefined, just as mine does. Further, the matched scores aren't skipped, which they should be.
Jeremy's script specifies lowest as a ko.observable. My script also now has lowest as a ko.observable, but why shouldn't a plain JS array work for this? I only need lowest to update when the button it's bound to is clicked, and those bindings are already taken care of.
That is how observables work in Knockout.
When you create one, you are creating a function.
var myObservable1 = ko.observable(); // Create it.
var myObservable2 = ko.observable("Hola!"); // Create it with a value.
console.log(typeof myObservable2); // It is indeed a function
console.log(typeof myObservable2()); // That returns a string
console.log(myObservable2()); // And get the value.
EDIT BASED ON QUESTION IN COMMENTS
var koTest = ko.observableArray();
koTest.push("Line0");
koTest.push("Line1");
koTest.push("Line2");
koTest.push("Line3");
koTest.push("Line4");
var jsTest = [];
jsTest.push("Line0");
jsTest.push("Line1");
jsTest.push("Line2");
jsTest.push("Line3");
jsTest.push("Line4");
alert(koTest()[2]);
alert(jsTest[2]);
alert(koTest()[2] === jsTest[2]);
Test Code
I went ahead and make a runnable test of your code and everything was working just fine for me. I had to make some assumptions about the contents of _this -- in particular the declaration of lowest, which I made an observableArray based on how you were accessing it.
Anyways, this code runs:
var _this = {
scores: ko.observableArray(),
lowest: ko.observableArray()
};
var mean = (function(scores) {
var m = 0;
var count = 0;
var k;
ko.utils.arrayForEach(_this.scores(), function(score) {
console.log([typeof score(), score()]);
if (!isNaN(parseFloat(score()))) {
k = _this.scores.indexOf(score);
console.log(k);
console.log(_this.lowest[k]);
if (score() != _this.lowest[k]) {
m += parseFloat(score());
count += 1;
}
}
});
if (count) {
m = m / count;
return m.toFixed(2);
} else {
return 'N/A';
}
});
for (var i = 0; i < 10; i++) {
_this.scores.push(ko.observable(i));
}
var m = mean();
alert(m);

passing array to function - dont get updated

Sorry for the question but I am new to JavaScript
i have defined an object
define(['sharedServices/pubsub', 'sharedServices/topics'], function (pubsub,topics) {
'use strict';
function Incident() {
var that = this;
this._dtasks = [];
this.handlePropertyGet = function(enstate, ename) {
if (!this.entityAspect || !this.entityAspect.entityManager || !this.entityAspect.entityManager.isReady) {
enstate = [];
} else {
enstate = this.entityAspect.entityManager.executeQueryLocally(new breeze.EntityQuery(ename).where('IncidentID', 'eq', this.IncidentID));
}
return enstate;
};
Object.defineProperty(this, 'DTasks', {
get: function () {
return this.handlePropertyGet(this._dtasks, "DTasks");
},
set: function (value) { //used only when loading incidents from the server
that.handlePropertySet('DTask', value);
},
enumerable: true
});
}
return {
Incident: Incident
};
});
when I am calling the property DTasks the inner member _dtask is equal to [], even when i enter the get property and i see that the enstate is filled with the objects when the handlePropertyGet is finished and returned to the get scope the _dtasks remains empty, doesn't it supposed to pass as reference?
this._dtasks "points" to an array. If you pass it as a parameter to this.handlePropertyGet, you make enstate refer to the same array.
If you change the array (as in enstate.push("bar")), the change affects this._dtasks too: you are actually changing neither of them, just the array they both point to.
However, the lines
enstate = []
and
enstate = this.entityAspect.entityManager.executeQueryLocally(new breeze.EntityQuery(ename).where('IncidentID', 'eq', this.IncidentID));
don't modify the array you already have. Instead, they create new arrays and change enstate so that it points to them. this._dtasks, however, remains unchanged.
An easy way to fix it would be to change the code inside the getter to
return this.handlePropertyGet("_dtasks", "DTasks");
and handlePropertyGet to
this.handlePropertyGet = function(enstate, ename) {
if (!this.entityAspect || !this.entityAspect.entityManager || !this.entityAspect.entityManager.isReady) {
this[enstate] = [];
} else {
this[enstate] = this.entityAspect.entityManager.executeQueryLocally(new breeze.EntityQuery(ename).where('IncidentID', 'eq', this.IncidentID));
}
return this[enstate];
};
That way, you would be changing the value of this._dtasks directly.
As an alternative, you could achieve the same result by changing enstate = [] to enstate.length = 0 (which clears the array instead of changing the variable. See https://stackoverflow.com/a/1232046/3191224) and enstate = this.entityAspect.[...] to
var newContent = enstate = this.entityAspect.entityManager.executeQueryLocally(new breeze.EntityQuery(ename).where('IncidentID', 'eq', this.IncidentID));
enstate.length = 0;
Array.prototype.push.apply(enstate, newContent);
which clears the array and then pushes all the elements from the other array, effectively replacing the whole content without changing enstate itself.
My guess is that you are trying to do something like this
Javascript
function Incident() {
var reset = false;
this._dtasks = [];
this.handlePropertyGet = function (ename) {
if (reset) {
this._dtasks = [];
} else {
this._dtasks = [1, 2, 3];
}
return this._dtasks;
};
Object.defineProperty(this, 'DTasks', {
get: function () {
return this.handlePropertyGet("DTasks");
},
enumerable: true
});
}
var x = new Incident();
console.log(x.DTasks);
Output
[1, 2, 3]
On jsFiddle
So you can then use this simplified example with the ideas given by #user3191224

how to turn this to into a tree?

I was doing a challenge of building a tree from all html elements. And I am 90% done, but I got stuck...
How do I change this string into a tree?:
mystring= "red1/(none)-red2/red1-blue1/red2-blue2/red2-blue3/red2-red3/red1-red4/red3-red5/red4-red6/red5-blue4/red6";
After splitting them by "-" we will have:
10 groups of -> (parameter1)/(parameter2)
The first parameter it is the object,
The second parameter is the 'in-what-it-will-be-contained'
I have no idea how to move every 'parameter1' inside 'parameter2'. (note: sometimes the parameter1 will be the parameter2 of a parameter1)
Visual example of what I mean with a parameter is inside another parameter: (this example uses exactly the string above)
Probably we should use arrays?, idk... I am totally lost :sadface:
I think this is a little more concise and straight forward. It uses an object as a dictionary to lookup the parent, rather than a function that has to recursively iterate the tree to find the parent. That recursive function is expensive. An object lookup is quick.
First, for convenience, I'd define an object type:
function TreeNode(name) {
this.Name = name;
this.Children = [];
}
Then I'd add a method to do the work. This parses your tree string:
TreeNode.ParseTree = function (treeString) {
var root = new TreeNode("");
var nodes = {};
var pairs = treeString.split("-");
pairs.forEach(function(pair) {
var parts = pair.split("/");
var parentName = parts[1];
var childName = parts[0];
var node;
if (parentName == "(none)") {
node = root;
root.Name = childName;
}
else {
node = new TreeNode(childName);
nodes[parentName].Children.push(node);
}
nodes[childName] = node;
});
return root;
};
That's it! Now, to get visual representations of your tree, you can add some prototype methods to TreeNode. First, override .toString():
TreeNode.prototype.toString = function(indent) {
indent = indent || "";
var strings = [indent + this.Name];
this.Children.forEach(function(child) {
strings.push(child.toString(indent + " "));
});
return strings.join("\n");
};
Then, add a .Render() method to display the tree within a web page:
TreeNode.prototype.Render = function(container) {
var nodeEl = container.appendChild(document.createElement("div"));
nodeEl.className = "treeNode";
var nameEl = nodeEl.appendChild(document.createElement("div"));
nameEl.className = "treeNodeName";
nameEl.appendChild(document.createTextNode(this.Name));
var childrenEl = nodeEl.appendChild(document.createElement("div"));
childrenEl.className = "treeNodeChildren";
this.Children.forEach(function(child) {
child.Render(childrenEl);
});
return nodeEl;
};
Here it is in action: http://jsfiddle.net/gilly3/wwFBx/
Edit: I didn't notice the jQuery tag in your post, here's a render method that's all jQuery, and produces simpler HTML which you seem to imply is what you want:
TreeNode.prototype.Render = function(container) {
var el = $("<div>").appendTo(container).text(this.Name);
$.each(this.Children, function() {
this.Render(el);
});
return el;
};
This JSFiddle uses jQuery, even replacing Array.forEach with $.each: http://jsfiddle.net/wwFBx/1/
As an alternative, you might consider just serializing your tree as JSON. Eg:
"{\"Name\":\"red1\",\"Children\":[{\"Name\":\"red2\",\"Children\":[{\"Name\":\"blue1\",\"Children\":[]},{\"Name\":\"blue2\",\"Children\":[]},{\"Name\":\"blue3\",\"Children\":[]}]},{\"Name\":\"red3\",\"Children\":[{\"Name\":\"red4\",\"Children\":[{\"Name\":\"red5\",\"Children\":[{\"Name\":\"red6\",\"Children\":[{\"Name\":\"blue4\",\"Children\":[]}]}]}]}]}]}"
or maybe:
"{\"red1\":{\"red2\":{\"blue1\":{},\"blue2\":{},\"blue3\":{}},\"red4\":{\"red5\":{\"red6\":{\"blue4\":{}}}}}}"
Parse the string via JSON.parse().
Disclaimer: I've referenced Array.forEach() and JSON.parse() which are built-in to modern browsers but are not supported by older browsers. To enable these functions in older browsers, see this documentation on Array.forEach() and this shim for JSON.parse().
Here's about how I would do it, using an array of "unplaced" elements and looping through it until they're all placed:
var str = "red1/(none)-red2/red1-blue1/red2-blue2/red2-blue3/red2-red3/red1-red4/red3-red5/red4-red6/red5-blue4/red6";
var unplaced = [];
var tree = null;
var elements = str.split(/[\/\-]/);
function findNodeByName(nodeName, context) {
if(context.name === nodeName) return context;
for(var i = 0; i < context.children.length; i++) {
var subSearch = findNodeByName(nodeName, context.children[i]);
if(subSearch) return subSearch;
}
return null;
}
var element, node, parent, thisElement, i;
for(i = 0; node = elements[i]; i += 2) {
node = elements[i];
parent = elements[i + 1];
thisElement = {name: node, children: []};
if(!tree && parent === '(none)') {
tree = thisElement;
} else if(tree) {
var parentNode = findNodeByName(parent, tree);
if(parentNode) {
parentNode.children.push(thisElement);
} else {
unplaced.push(thisElement);
}
}
}
var oldLength;
while(unplaced.length) {
oldLength = unplaced.length;
for(i = 0; element = unplaced[i]; i++) {
var parentNode = findNodeByName(parent, tree);
if(parentNode) {
parentNode.children.push(element);
unplaced.splice(i, 1);
i--;
}
}
if(oldLength === unplaced.length) {
throw new SyntaxError("The string is not a valid tree.");
}
}
// The result is contained in "tree".
You can see the result at: http://jsfiddle.net/minitech/tJSpN/
One with a function: http://jsfiddle.net/minitech/tJSpN/1/
And one with more error-checking: http://jsfiddle.net/minitech/tJSpN/2/
Actually, I found a simpler/shorter/neater way using the JQuery function AppendTo()
We just need to:
Split the parameters...
Create one div for each (parameter1)
Use a loop to move every (parameter1) inside (parameter2) using the
AWESOME AppendTo() function that JQuery offers
The best thing is that they are actually inside them, so you can easily put a Hide/Show effect to make a cool effect
You may try to create tree nodes of the form :
node = {
str:"red1",
subBranches : new Array()
}
Once you have that, you may add the sub-branches iterating through the array, adding such nodes for each found correct couple, and removing the couples already placed in rootNode.subBranches. Then you recursively do the same for every sub-branche.

Categories

Resources