Function not returning the volume value - javascript

i was wondering why this function its not working as far as my understanding goes(newbie) when invoking i should have the value[0] and [1] in order to get the result that i am looking for but i have tried in the browser and in console.log and i am not getting the [1] return value as expected.
function getSize(width, height, depth) {
var area = width * height;
var volume = width * height * depth;
var sizes = [area, volume];
alert(area);
}
var areaOne = getSize(3, 2, 1)[0];
var volumeOne = getSize(2, 1, 5)[1];

Here you are missing return.
A function should always return value.
function getSize(width,height,depth){
var area =width * height;
var volume=width*height*depth;
var sizes=[area,volume];
//alert(area);
return area;
}
var areaOne=getSize(3,2,1)[0];
var volumeOne=getSize(2,1,5)[1];
console.log(volumeOne)

You should return the value form you function in order to retrieve the values.
function getSize(width,height,depth){
var area =width * height;
var volume=width*height*depth;
var sizes=[area,volume];
return [volume, area]; // you should reuren the value in order to get it
}
var areaOne=getSize(3,2,1)[0];
var volumeOne=getSize(2,1,5)[1];
console.log(areaOne, volumeOne);

Your function doesn't have a return parameter, in order to assign functions output (in this case sizes[] array) your function needs to return that value, just add return sizes; at the end of your function definition.

Related

function isn't being called in JavaScript graphics

I was making a tic tac toe game in JavaScript graphics (I think) and I called a function to get the row of the click (the function that isn't working is the getRow function) and there isn't any output from the function
var WIDTH = 400;
var HEIGHT = 400;
setSize(WIDTH, HEIGHT);
var WINNING_LINE_WIDTH = 10;
var WINNING_LINE_COLOR = Color.red;
//high
var width = getWidth() / 3;
//thick
var height = getHeight() / 3;
//x != o
var shape = 0;
//1 2 3, as easy as A B C
var row = 0;
//ready, set, GO!!!!
function start(){
grid();
mouseClickMethod(click);
}
//lines
function grid(){
var line1 = new Line(width, 0, width, getHeight());
var line2 = new Line(width * 2, 0, width * 2, getHeight());
var line3 = new Line(0, height, getWidth(), height);
var line4 = new Line(0, height * 2, getWidth(), height * 2);
add(line1);
add(line2);
add(line3);
add(line4);
}
//notrick
function click(e){
var clicky = e.getY();
getRow(clicky,row);
println(row);
println(clicky);
println(height);
println(height * 2);
println(height * 3);
}
//row row row ur boat
function getRow(clicky, row){
if(clicky < height){
return row + 1;
} if(clicky >= height && clicky <= height * 2 ){
return row + 2;
} else{
return row + 3;
} return row - 1;
println("nothing");
}
This code is working properly for what you wrote, but there are a few things you'll want to change to get your intended functionality.
First, functions' return values are returned through the array call itself. It seems that in your example code you're passing in "clicky" and "row" as arguments, and trying to set the value of those variables in the function. When you create parameters though, you're actually overwriting any other variables in the current scope with the same name and creating local variables instead, and you're just passing in the value of the variables n your function call. So this is what's happening in your program:
var row = 0;
function getRow(row) {
// defining row as a parameter creates a new local variable called "row"
row = 1; // sets the "row" local variable to 1, but doesn't affect the "row" outside of the function
console.log(row); // prints "1" because that's the value of the local var
}
getRow(row);
console.log(row); // prints 0 because that's the value of the global variable "row"
So what you'll want to do is pass in your cursor's y-value on click (which you already are doing! It saves it as the function parameter "clicky") but you do not need to pass in the row too.
Then, you can just return an integer for your row value! (Instead of adding it to the global variable as you are right now) Then all you have to do is actually set row to that value, by setting row equal to the function call.
// variable values for example
var row = -1;
var height = 100 / 3; // each row will be ~33 pixels
function click(e){
var clicky = e.getY();
row = getRow(clicky); // set row to the value returned from getRow()!
}
//row row row ur boat
function getRow(clicky){
if(clicky < height){
return 1;
} if(clicky >= height && clicky <= height * 2 ){
return 2;
} else{
return 3;
} return -1;
println("nothing"); // also note: you can delete this as it will never run, as its after a return (which stops running the function)
}
// testing:
console.log(row); // before click (-1)
click({getY:()=>0}); // test object I made so it can get a y-value (it'll just be your click event in your code)
console.log(row); // after clicking at y = 0 (0)
click({getY:()=>40});
console.log(row); // after clicking at y = 40 (1)
click({getY:()=>90});
console.log(row); // after clicking at y = 90 (2)
Hope this helped! If you need clarification on anything just let me know.

How to get the next element on Map function?

I'm trying to make some coordinate plane functions on React native. But I'm having a problem that I don't know how to get the next element on my array.
This is my array:
[
{"M":["0","0"]},
{"H":"100"},
{"V":"0"},
{"H":"100"},
{"V":"100"},
{"H":"0"},
{"V":"100"},
{"H":"0"},
{"V":"0"},
]
This is my function:
const rotate = (pathArray, angle) =>{
if (angle > 0){
let vCordinate;
return pathArray.map((cordinate)=>{
if(Object.entries(cordinate)[0][0] == "M"){
let mCordinate = Object.entries(cordinate)[0][1];
mCordinate[0] = (parseInt(mCordinate[0]) * Math.cos(angle)) - (parseInt(mCordinate[1]) * Math.sin(angle));
mCordinate[1] = (parseInt(mCordinate[1]) * Math.cos(angle)) + (parseInt(mCordinate[0]) * Math.sin(angle));
return {[Object.entries(cordinate)[0][0]]: mCordinate};
}
//LOGIC TO GET NEXT ELEMENT
if(Object.entries(cordinate)[0][0] == "H"){
let hCordinate = Object.entries(cordinate)[0][1];
vCordinate = Object.entries(cordinate)[0][1]
return {[Object.entries(cordinate)[0][0]]: vCordinate};
}
if(Object.entries(cordinate)[0][0] == "V"){
return {[Object.entries(cordinate)[0][0]]: vCordinate};
}
})
}
return pathArray;
}
In this point I need to get the next element when I've hit "H".
How to do this?
The callback of map method accepts 3 arguments:
current item value;
current item index;
the array map was called upon.
So, you could use index to get next element value:
var newArray = myArray.map(function(value, index, elements) {
var next = elements[index+1];
// do something
});
or
var newArray = myArray.map(function(value, index) {
var next = myArray[index+1];
// do something
});
Note, the value of next variable may be undefined. Test the variable, if need, to prevent errors.

Object variable is undefined even though it's initialised

I have a Node project where I create a Unit and an AddGate:
var Unit = function(value, weight) {
this.value = value;
this.weight = weight;
}
var AddGate = function() {
this.sum_function = function(units) {
sum = 0;
for (unit in units)
sum += unit.value;
return sum;
};
};
AddGate.prototype = {
forward: function(units) {
this.units = units;
this.output_unit = new Unit(this.sum_function(units), 0.0);
return this.output_unit;
}
}
I create some Units, an AddGate, and a ForwardNeuron (guess what I'm making):
var in_1 = new Unit(1.0, 0.0);
...
var in_9 = new Unit(3.0, 0.0);
var add = new AddGate();
var forwardNeuron = function() {
a = add.forward({in_1, in_2, in_3, in_4, in_5, in_6, in_7, in_8, in_9});
};
forwardNeuron();
But for some reason, when in sum_function of AddGate, I can access each unit of units fine, but when I try to access unit.value, it says it's undefined, even though I've clearly initialised it. Am I missing something?
As the comments specify, for (let unit in units) will actually set unit as the key of the units object. You can correct this in a few ways such as using units[unit].value, but it would make more sense to me for the arguments to forward and sum_function to be an array. More or less as simple as:
add.forward([in_1, in_2, in_3, in_4, in_5, in_6, in_7, in_8, in_9]);
The sum would be a reduce operation on the array as in:
return units.reduce((sum, unit) => sum + unit.value, 0);
FYI 4castle's response worked for me - I wrote:
sum += units[unit].value;
That did the trick for me. Thanks again to 4castle and trincot for their speedy responses.
EDIT: The above is even better.

return biggest/highest object from jquery elements

Howdey!
Let's take a look at the following jQuery function:
$.fn.getMax = function() {
return this.height(Math.max.apply(this, $(this).map(function(i, e) {
return $(e).height();
}).get()));
};
It returns and sets the heighest height for all selectors. But what is, if you want to return the object (not the height) with the heighest value?
So if you call the function like this:
$(selector).getMax().css({backgroundColor: "indigo"});
...how the element with the heighest height gets the backgroundColor?
UPDATE
I've managed it now with $.makeArray, as Amareswar said it.
$.fn.getMax = function(prop) {
var max = $.makeArray($(this)).sort(function(a, b) {
return (parseInt($(b).css(prop), 10) || 1) - (parseInt($(a).css(prop), 10) || 1);
}).shift();
return $(max);
};
Cheers!
Try this:
$.fn.getMax = function() {
/* create array of heights*/
var heights = $(this).map(function(i, e) {
return $(e).height();
}).get();
/* get max height*/
var max = Math.max.apply(this, heights);
/* get index of max in array*/
var pos = $.inArray(max, heights)
/* return element with proper index*/
return this.eq(pos);
};
DEMO: http://jsfiddle.net/tTuE7/
EDIT : assumes you only want one element returned

jQuery - setInterval issue

I am using jQuery to generate and add a random amount of Clouds to the Header of the page and move them left on the specified interval. Everything is working fine, execpt the interval only runs once for each Cloud and not again. Here is my code:
if(enableClouds) {
var cloudCount = Math.floor(Math.random() * 11); // Random Number between 1 & 10
for(cnt = 0; cnt < cloudCount; cnt++) {
var cloudNumber = Math.floor(Math.random() * 4);
var headerHeight = $('header').height() / 2;
var cloudLeft = Math.floor(Math.random() * docWidth);
var cloudTop = 0;
var thisHeight = 0;
var cloudType = "one";
if(cloudNumber == 2) {
cloudType = "two";
}else if(cloudNumber == 3) {
cloudType = "three";
}
$('header').append('<div id="cloud' + cnt + '" class="cloud ' + cloudType + '"></div>');
thisHeight = $('#cloud' + cnt).height();
headerHeight -= thisHeight;
cloudTop = Math.floor(Math.random() * headerHeight);
$('#cloud' + cnt).css({
'left' : cloudLeft,
'top' : cloudTop
});
setInterval(moveCloud(cnt), 100);
}
function moveCloud(cloud) {
var thisLeft = $('#cloud' + cloud).css('left');
alert(thisLeft);
}
}
Any help is appreciated!
This is the way to go:
setInterval((function(i){
return function(){
moveCloud(i);
};
})(cnt), 100);
Engineer gave you the code you need. Here's what's happening.
The setInterval function takes a Function object and an interval. A Function object is simply an object that you can call, like so:
/* Create it */
var func = function() { /* ... blah ... */};
/* Call it */
var returnVal = func(parameters)
The object here is func. If you call it, what you get back is the return value.
So, in your code:
setInterval(moveCloud(cnt), 100);
you're feeding setInterval the return value of the call moveCloud(cnt), instead of the the function object moveCloud. So that bit is broken.
An incorrect implementation would be:
for(cnt = 0; cnt < cloudCount; cnt++) {
/* ... other stuff ... */
var interval = setInterval(function() {
moveCloud(cnt);
}, 100);
}
Now, you're feeding it a function object, which is correct. When this function object is called, it's going to call moveCloud. The problem here is the cnt.
What you create here is a closure. You capture a reference to the variable cnt. When the function object that you passed to setInterval is called, it sees the reference to cnt and tries to resolve it. When it does this, it gets to the variable that you iterated over, looks at its value and discovers that it is equal to cloudCount. Problem is, does not map on to a Cloud that you created (you have clouds 0 to (cloudCount -1)), so at best, nothing happens, at worst, you get an error.
The right way to go is:
setInterval((function(i){
return function(){
moveCloud(i);
};
})(cnt), 100);
This uses an 'immediate function' that returns a function. You create a function:
function(i){
return function(){
moveCloud(i);
};
}
that returns another function (let's call it outer) which, when called with a value i, calls moveCloud with that value.
Then, we immediately call outer with our value cnt. What this gives us is a function which, when called, calls moveCloud with whatever the value of cnt is at this point in time. This is exactly what we want!
And that's why we do it that way.

Categories

Resources