How would I call my method to my other objects?
Been having lots of trouble with everything I've tried.
I'm not that confident with this stuff, just looking on how to tell if the object is safe to drive or not.
//Create a constructor function called `Track`. It will accept two parameters - the name of the track and the maximum capacity of the track.
let track = function(name, capacity){
this.trackName=name
this.personnel=0;
this.cars=[];
this.cap=capacity;
}
//We'll need a value for the average weight of a person but this value will be the same for all tracks.
//Add a property `personWeight` on the `Track` prototype so that all instances share the same value.
track.prototype.personWeight = 200
//Create three methods on the prototype that will calculate track weight, person weight, and if its safe to drive
function personWeight(){
personnelWeight = this.personWeight * this.personnel
return personnelWeight
}
function trackWeight(){
let carsTotal = function myFunc(total, num) {
return total - num;
}
let weightTotal = (this.personnel * this.personWeight) + (this.carsTotal)
return weightTotal
}
function safeToDrive(){
if(this.trackWeight<this.capacity){
return true
}
}
//Create two track objects
let trackOne = new track ("Daytona", 25000);
trackOne.cars = [1800, 2400, 2700, 3200, 3600, 3800, 4200]
trackOne.personnel = 10
let trackTwo = new track ("Indiana",15000);
trackTwo.cars = [2000, 2300, 2800, 3000, 3500, 3700, 4000]
trackTwo.personnel = 8
//Call the `safeToDrive` method for truck objects.
With the code as it is now, you would use safeToDrive.call(trackOne). However, this is not the straight-forward way you would do it normally.
I guess what you really want is assigning these methods to the prototype:
track.prototype.safeToDrive = function () {
if(this.trackWeight<this.capacity){
return true
}
}
Then you'd call them using trackOne.safeToDrive().
The same goes for personWeight and trackWeight.
A few other observations:
Your check for this.capacity won't work because the property is actually called cap and not capacity according to what you set in your constructor.
safeToDrive currently returns true or nothing, i.e. undefined, and not true or false as you would expect.
You could fix that by either adding an else with return false or simply using return this.trackWeight < this.capacity instead of the whole if condition.
Oh, also, your personnelWeight variable is accidentally made global. Add a let before it. To avoid this in the first place, add 'use strict' at the top of your file to get warned about this issue next time.
I'm not sure what you are doing with carsTotal there though, I guess that should be a member function as well (otherwise you couldn't even call it using this.carsTotal as you do now). Plus, your indention is wrong there. (Put your file through a beautifier to see what I mean.)
Do you mean truck instead of track maybe...?
Related
I'm doing a simple constructor exercise and I need to change a value after the initial creation of the constructor. When I run it the cat is still not making its noise after I changed its value to true.
Challenge parameters
The constructor function will take in two parameters, raining and noise. These will be passed into the keys as their value.
Create a third key that will be a function called makeNoise(). The function checks if the raining key's value is true. If it is, it will log the value of the key's noise in the console.
Bonus
How can we make the cat make noise? In other words, how can we change the value of raining for the cat object after it has been created?
function Animal(raining, noise) {
this.raining = raining,
this.noise = noise;
this.makeNoise = function(){
if(this.raining)
console.log(noise)
}
}
// Creates `dog` and `cat` objects with `raining` and `noise` properties
let dog = new Animal(true, 'Woof!');
let cat = new Animal(false, 'Meow!');
// Calls the `makeNoise()` methods on the `dog` and `cat` objects
dog.makeNoise();
cat.makeNoise();
// BONUS CODE HERE
cat.raining= true;
You have to call makeNoise() after setting the raining property to true. When you call makeNoise() before, the raining property is false (since JS is (mostly) executed sequentially), so nothing is logged.
function Animal(raining, noise) {
this.raining = raining,
this.noise = noise;
this.makeNoise = function() {
if (this.raining)
console.log(noise)
}
}
// Creates `dog` and `cat` objects with `raining` and `noise` properties
let dog = new Animal(true, 'Woof!');
let cat = new Animal(false, 'Meow!');
// Calls the `makeNoise()` methods on the `dog` and `cat` objects
dog.makeNoise();
cat.makeNoise();
// BONUS CODE HERE
cat.raining = true;
cat.makeNoise();
I am following a course on blockchain which has the following piece of code.
What does " index:this.chain.length+1 " mean? Is index a variable in the object newBlock? Or is it a key value pair? If it is a variable, why don't we simply use index=this.chain.length+1? Also what is the type of the object newBlock?
function Blockchain()
{
this.chain=[];
this.newTranscations=[];
}
Blockchain.prototype.createNeBlock = function(nonce,previousBlockHash,hash)
{
const newBlock ={
index:this.chain.length+1,
timestamp:Date.now(),
// all of the transactions in this block will be the transactions that waiting to be put in a block
transactions:this.newTranscations,
// nonce is hust a number giving proof of the transaction
nonce:nonce,
hash:hash,
previousBlockHash: previousBlockHash
}
// As we move all the pending transactions to the new block, we clear this array
this.newTranscations=[];
this.chain.push(newBlock);
return newBlock;
}
var Box = {
"playdoh":{"playdoh":["none", "some", "none", "none", "some"]}
};
Box of playdoh upon playdoh, you're getting into the study of Objects/Arrays/Maps.
To call the above out, it'd be
console.log(Box["playdoh"]["playdoh"][0]);
= none
console.log(Box["playdoh"]["playdoh"][4]);
= some
console.log(Box["playdoh"]["playdoh"][5]);
= null (undefined)
is the same as
console.log(Box.playdoh.playdoh[0]);
= none
console.log(Box.playdoh.playdoh[4]);
= some
console.log(Box.playdoh.playdoh[5]);
= null (undefined)
It is one of several ways to initialize an object called newBlock in javascript. Take a look at this documentation on MDN
The index property is of type number in this case, and it is set to equal chain[].length + 1
Im encountering an odd problem when going through freeCodeCamp beta.
The "purpose" of this is not modifying the original array and using functional programming techniques to modify arrays.
However I keep getting complaints about the "array" parameter is the remove function not being a valid function:
// the global variable
var bookList = [
"The Hound of the Baskervilles",
"On The Electrodynamics of Moving Bodies",
"PhilosophiƦ Naturalis Principia Mathematica",
"Disquisitiones Arithmeticae"];
/* This function should add a book to the list and return the list */
// New parameters should come before the bookName one
// Add your code below this line
function add (bookListTemp, bookName) {
let newBookArr = bookListTemp;
return newBookArr.push(bookName);
// Add your code above this line
}
/* This function should remove a book from the list and return the list */
// New parameters should come before the bookName one
// Add your code below this line
function remove (bookList,bookName) {
let newArr = bookList.slice();
if (newArr.indexOf(bookName) >= 0) {
return newArr.slice(0, 1, bookName);
// Add your code above this line
}
}
var newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'),
'On The Electrodynamics of Moving Bodies');
console.log(bookList);
In the remove function i've tried taking the parameter and doing array.slice() method as well as array.concat() method. Since doing let newArr = bookList doesn't actually make a new array correct? it just makes a new copy that references the original array correct?
The exact error I get is TypeError: bookList.slice is not a function
What's even weirder is Array.isArray(bookList) returns true (in the function remove. So I don't understand why it's complaining about array methods?
Your problem is Array.push
return The new length property of the object upon which the method was
called.
You should return array instead
function add (bookListTemp, bookName) {
let newBookArr = bookListTemp;
newBookArr.push(bookName);
// Add your code above this line
return newBookArr;
}
OR
Let's try Array.concat instead
function add (bookListTemp, bookName) {
let newBookArr = bookListTemp;
return newBookArr.concat(bookName);
// Add your code above this line
}
There are two ways to copy the array without mutating it. You will not be able to use the .slice() method on the bookList, because it is an argument in the function and therefore not an array. The work around is var newBookArr = Array.prototype.slice.call(bookListTemp); or [].slice.call(bookListTemp);
This allows you to perform the slice on the bookList when it is an argument. The other way I discovered, when playing around with it - var newBookArr = [].concat(bookListTemp);
When trying var newBookArr = [].push(bookListTemp); we find the original bookList pushed inside the new array. So it is a copy, but as an array within an array. the .concat() method merges the old array into the new.
i am having a problem that i am finding difficult to find information about as i am unaware of the underlying issue.
I am trying to set a property inside an object, and when i console.log the property it gives the anticipated result but when i console.log the entire object, the property inside is different.
defaults:{
uid:undefined,
createSphere:function(uid,coordinates)
{
this.uid = uid;
console.log(this.uid);
console.log(uid);
console.log(this);
console.log(this.uid);
I run the createSphere function in a simple for loop. Here you can see how i assign the uid for the function.
for(i = 0;i<n;i++)
{
coordinates = {x:0,y:5,z:0}
coordinates.x = 0+ (40*Math.sin(Math.PI*(i/2)))
coordinates.z = 0+ (40*Math.cos(Math.PI*(i/2)))
spheres.defaults.createSphere((i+1),coordinates);
}
Here you can see the resulting log when creating the first sphere with the code from the first block. The console.logs are executed directly after eachother, so nothing is able to change the value between the logging. I wanted to upload it in an image for better clarity but i unfortunately cannot.
1
1
Object
action: function (order,impulseVector){
createSphere: function (uid,coordinates)
uid: 2
__proto__: Object
1
So the problem is; when taking the value directly from the property it differs from when using the entire object.
When you call:
spheres.defaults.createSphere((i+1),coordinates);
It isn't creating a new sphere object. Instead it is only updating "spheres.defaults.uid".
Perhaps this is closer to what you are looking for:
var Sphere = function(uid, coordinates){
this.uid = uid;
this.coordinates = coordinates;
}
var spheres = [];
spheres.push(new Sphere(1, null));
spheres.push(new Sphere(2, null));
spheres.push(new Sphere(3, null));
spheres.push(new Sphere(4, null));
console.log(spheres);
I have a function that uses the underscore.js each function to just call a string replace on each item in a list. (Actually a pair of lists):
//Base object
buckets = {
counters: ["stats.REPLACE.msg_delivered",
"stats.REPLACE.delivery_failed"],
timers: ["stats.timers.REPLACE.msg_delivery_timer.median",
"stats.timers.REPLACE.msg_delivery_timer.mean",
"stats.timers.REPLACE.msg_delivery_timer.std",
"stats.timers.REPLACE.msg_delivery_timer.upper"]
};
//function in question
_getNodeTargets = function(node) {
var targets = buckets;
_.each(targets.counters, function(bucket) { bucket = bucket.replace("REPLACE", node);});
_.each(targets.timers, function(bucket) { bucket = bucket.replace("REPLACE", node);});
return targets;
}
I can step into the each function and see that the strings are being replaced and assigned back to bucket. However, when I hit the return the targets object is unchanged with REPLACE still in each of the strings.
I have no doubt I am doing something dumb but for whatever reason I just can't see it.
Thanks in advance!
You have to make use of the other arguments _.each gives your callback:
_.each(targets.counters,
function(bucket, i, target) {
target[i] = bucket.replace("REPLACE", node);
});
The reason for this is that bucket itself is a reference to a string; replacing that reference with one of your own does not also replace the reference stored in the collection (that keeps pointing to the unmodified version). In contrast, target[i] does go and update the collection so the change is visible even after your callback returns.