I have a javascript function:
function myFunction(value1,value2,value3)
{
//Do stuff and
value2=somevalue2 //to return
value3=somevalue3 //to return
}
function call in Code:
....
myFunction("1",value2,value3);
if(value2 && value3)
{
//Do some stuff
}
in this scenario how to pass value2 and value3 to the called method or how to return values in Java script.
You can return an array, an object literal, or an object of a type you created that encapsulates the returned values.
Then you can pass in the array, object literal, or custom object into a method to disseminate the values.
Object example:
function myFunction(value1,value2,value3)
{
var returnedObject = {};
returnedObject["value1"] = value1;
returnedObject["value2"] = value2;
return returnedObject;
}
var returnValue = myFunction("1",value2,value3);
if(returnValue.value1 && returnValue.value2)
{
//Do some stuff
}
Array example:
function myFunction(value1,value2,value3)
{
var returnedArray = [];
returnedArray.push(value1);
returnedArray.push(value2);
return returnedArray;
}
var returnValue = myFunction("1",value2,value3);
if(returnValue[0] && returnValue[1])
{
//Do some stuff
}
Custom Object:
function myFunction(value1,value2,value3)
{
var valueHolder = new ValueHolder(value1, value2);
return valueHolder;
}
var returnValue = myFunction("1",value2,value3);
// hypothetical method that you could build to create an easier to read conditional
// (might not apply to your situation)
if(returnValue.valid())
{
//Do some stuff
}
I would avoid the array method because you would have to access the values via indices rather than named object properties.
Javascript is duck typed, so you can create a small structure.
function myFunction(value1,value2,value3)
{
var myObject = new Object();
myObject.value2 = somevalue2;
myObject.value3 = somevalue3;
return myObject;
}
var value = myFunction("1",value2,value3);
if(value.value2 && value.value3)
{
//Do some stuff
}
function myFunction(value1,value2,value3)
{
return {val2: value2, val3: value3};
}
It's difficult to tell what you're actually trying to do and if this is what you really need but you might also use a callback:
function myFunction(value1,callback)
{
//Do stuff and
if(typeof callback == 'function'){
callback(somevalue2,somevalue3);
}
}
myFunction("1", function(value2, value3){
if(value2 && value3)
{
//Do some stuff
}
});
I would prefer a callback solution:
Working fiddle here: http://jsfiddle.net/canCu/
function myFunction(value1,value2,value3, callback) {
value2 = 'somevalue2'; //to return
value3 = 'somevalue3'; //to return
callback( value2, value3 );
}
var value1 = 1;
var value2 = 2;
var value3 = 3;
myFunction(value1,value2,value3, function(value2, value3){
if (value2 && value3) {
//Do some stuff
alert( value2 + '-' + value3 );
}
});
The return statement stops the execution of a function and returns a value from that function.
While updating global variables is one way to pass information back to the code that called the function, this is not an ideal way of doing so. A much better alternative is to write the function so that values that are used by the function are passed to it as parameters and the function returns whatever value that it needs to without using or updating any global variables.
By limiting the way in which information is passed to and from functions we can make it easier to reuse the same function from multiple places in our code.
JavaScript provides for passing one value back to the code that called it after everything in the function that needs to run has finished running.
JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return keyword.
Its very simple. Call one function inside another function with parameters.
function fun1()
{
var a=10;
var b=20;
fun2(a,b); //calling function fun2() and passing 2 parameters
}
function fun2(num1,num2)
{
var sum;
sum = num1+num2;
return sum;
}
fun1(); //trigger function fun1
The answers cover things very well. I just wanted to point out that the mechanism of out parameters, as described in the question isn't very javascriptish. While other languages support it, javascript prefers you to simply return values from functions.
With ES6/ES2015 they added destructuring that makes a solution to this problem more elegant when returning an array. Destructuring will pull parts out of an array/object:
function myFunction(value1)
{
//Do stuff and
return [somevalue2, sumevalue3]
}
var [value2, value3] = myFunction("1");
if(value2 && value3)
{
//Do some stuff
}
Related
I know that the purpose of memoize is to cache values so code can be run faster by not having to re-calculate the same answer everytime. My issue stems from returning a function (i think). The google chrome debugger isn't that useful for me here because everytime I try to run this memoize function, it just goes from the argus variable (on line 4 i believe) all the way down to the semi-colon. Furthermore, result always returns an empty object instead of storing a value in result.
I start by defining a function:
function add(a,b){
return a+b;
}
This is my attempt at the memoize function:
_.memoize = function(func) {
var result = {};
var flag = 0;
var argus = Array.prototype.slice.call(arguments)
return function() {
if(result[key] === arguments){
flag = 1
}
else if(flag = 0){
result[argus] = func.apply(this, argus);
}
return result[argus];
};
};
I'd call memoize by doing _.memoize(add(2,5)) but the result doesn't get stored in the result object.
Am I even close to getting this memoize function working properly? Any guidance you guys can give here would be appreciated.
The biggest point you're missing is that _.memoize is called on the function first, and it returns a new function. You are calling it on the result of a function call (which is the number 7 in this case).
In order to get it to work, you need to rearrange a few things.
Also note that it's not wise to try to use an array itself as the index to an object. One approach to get around that would be to convert the arguments array to JSON and use that as the index on the results object:
function add(a, b) {
console.log('Called add(' + a + ', ' + b + ')');
return a + b;
}
var _ = {};
_.memoize = function(func) {
var results = {};
return function() {
var args = Array.prototype.slice.call(arguments);
var key = JSON.stringify(args);
if (!(key in results)) {
results[key] = func.apply(this, args);
}
return results[key];
};
};
var madd = _.memoize(add);
console.log(madd(2, 4));
console.log(madd(9, 7));
console.log(madd(2, 4));
I have a function to which I pass an array or an object, then it looks for specific keys and edits their values accordingly,
function iterate(obj, delta) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property],delta);
} else {
if(property === 'unix_time'){
var bee = parseInt(obj[property]);
var b = bee + parseInt(delta);
obj[property] = b;
}
}
}
}
}
Basically, it looks for the "unix_time" key and add a number "delta" to it.
Question: When I call it asynchronous, it becomes undefined, How can I add a callback that I can simply use to determine that the function has finished executing. Or maybe should I add a promise to it?
For example when i run this it returns perfectly
console.log("new one", obj);
iterate(obj, 3600000)
But this is a problem, it becomes undefined
var dd = iterate(obj, 3600000);
res.status(200).send(JSON.stringify(dd));
As mentioned in comments, you function is synchronous and it returns immediately after you call it like this:
var result = iterate(tree, delta);
However, as it's currently written, the result variable will have value of undefined since your iterate function doesn't return anything.
If you have the setup like this:
var obj = {...};
iterate(obj, 3600000)
console.log(obj) // correctly outputs modified object
It will output modified object, since you're not using here the returned value from the function. However, in this scenario:
console.log("new one", iterate(obj, 3600000)); // ouputs `undefined`
the returned value is used and it's undefined.
Using the use case you provided, you can modify the usage like this:
iterate(obj, 3600000);
res.status(200).send(JSON.stringify(obj));
and it will work fine. Or you need to modify iterate to return value. Provide an example of obj so I can write a modification to your iterate function.
Modified the iterate function:
function iterate(obj, delta) {
obj.forEach(function (element) {
if (element.hasOwnProperty('unix_time')) {
element['unix_time'] = parseInt(element['unix_time']) + parseInt(delta);
}
});
return obj;
}
I don't know I understand your question. But, if you want to use a callback, you should split this funcion in two. One for main operation and another for recursivity.
i.e.
function iterate(obj, delta, callback) {
interate_recursive(obj, delta);
if(typeof callback != 'undefined')
return callback();
else return obj;
}
function interate_recursive(obj,delta){
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property],delta);
} else {
if(property === 'unix_time'){
var bee = parseInt(obj[property]);
var b = bee + parseInt(delta);
obj[property] = b;
}
}
}
}
}
I have a few functions in two different files that are all linked together by function calls they are as follows
FILE 1:
function getFunction(func){
}
FILE 2:
function Numbers(one, two) {
return (one*two);
}
var func = getFunction(Numbers);
and these are called by:
func(input_array);
my array has values 1,3,5,7,9 and I need func(input_array) to return 3,15,35,63,9 (the last value loops back to the first value)
basically what I am trying to do is have getFunction return a function such that these values are calculated. I am having trouble because I can't wrap my mind about sending and returning functions. I don't know how to access the array if it isn't sent into the function. Let me know if I need to clarify anything.
function getFunction(callback) {
return function(array) {
return array.map(function(cur, index) {
return callback(cur, array[(index+1) % array.length]);
});
};
}
getFunction returns a closure over the callback parameter, which is the function that you want to call. The closure receives the array parameter, and it calls the callback in a loop over the array using array.map. The % modulus operator performs the wraparound that you want.
Another way to write this that may be clearer is:
function getFunction(callback) {
return function(array) {
var result = [];
for (var i = 0; i < array.length; i++) {
j = (i+1) % array.length; // Next index, wrapping around
result.push(callback(array[i], array[j]));
}
return result;
};
}
var func = getFunction(Numbers);
console.log(func([1,3,5,7,9])); // Logs [3,15,35,63,9]
here is simple function that returns what you need
function Numbers(x) {
output_array=[];
for(i=0;i<x.length;i++){
if(x[i+1]==undefined){
output_array.push(x[i]);
}
else{
output_array.push(x[i]*x[i+1]);
}
}
return output_array;
}
var input_array=[1,3,5,7];
var num = Numbers(input_array);
console.log(num);
OR if you need it in the way function calling another function
and than returning the result use this
function getFunction(Numbers,input_array){
return Numbers(input_array);
}
function Numbers(x) {
output_array=[];
for(i=0;i<x.length;i++){
if(x[i+1]==undefined){
output_array.push(x[i]);
}
else{
output_array.push(x[i]*x[i+1]);
}
}
return output_array;
}
var input_array=[1,3,5,7];
var num = getFunction(Numbers,input_array);
console.log(num);
I have a very basic question about JavaScript.
Consider the following code:
var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function(item,index,array) {
alert(arguments.length);
return (item > 1);
});
Now in the above code I am passing anonymous function as an argument of "every" function.
How exactly my anonymous function is getting the exactly 3 arguments(item,index,array).
This isn't really a basic javascript question, but a library question, and how it "happens" depends on the implementation.
This here is a sample implementation of every in javascript:
function every(array, fn) {
for(var i = 0; i < array.length; i++) {
fn(array[i], i, array);
}
}
You would call it like this:
every([1,2,3,4], function(item, index, array) {
// do stuff
});
As you can see, it's the every function itself, that calls the fn (which is the function you pass in), and decides what arguments to pass.
The anonymous function you're passing is simply provided as argument for every() method which calls it for a number of times. every() iterates through your list items and calls your anonymous function each time with three arguments: value, index and your entire array.
Here's an approximate source code of how the actual every() function works:
Array.prototype.every = function(callback) {
for(i=0; i<this.length; i++) {
callback(this[i], i, this);
}
}
Let's build a simple function with a callback argument:
function foo(callback)
{
var callbackArgument = 'bar';
callback(callbackArgument);
}
Let's use it:
foo(function(arg){
console.log(arg);
}); // logs "bar" to the console!
How exactly my anonymous function is getting the exactly 3
arguments(item,index,array)?
Maybe it would be easier to understand with an alternative example You have:
var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function(item,index,array) {
alert(arguments.length);
return (item > 1);
});
You could also write the same in the following manner:
var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(item,index,array) {
function anonymous(firstVar,secondVar,thirdVar){
//do your anonymous stuff here
alert(thirdVar.length);
return (firstVar > 1);
}
//get the anonymous function processed data
var anonymousFunctionResults = anonymous(item,index,array);
//do your original stuff that you would have done with the results of anonymous function
anonymousFunctionResults...
}
});
Or in this way:
function anonymous(firstVar,secondVar,thirdVar){
//do your anonymous stuff here
alert(thirdVar.length);
return (firstVar > 1);
}
var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(item,index,array, anonymous) {
//get the anonymous function processed data
var anonymousFunctionResults = anonymous(item,index,array);
//do your original stuff that you would have done with the results of anonymous function
anonymousFunctionResults...
}
});
Or in this way:
function anonymous(firstVar,secondVar,thirdVar){
//do your anonymous stuff here
alert(thirdVar.length);
return (firstVar > 1);
}
var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(anonymous(item,index,array)) {
//get the anonymous function processed data
//you can use the "firstParameter" variable already of course
//this is just to make a point
var anonymousFunctionResults = firstParameter;
//do your original stuff that you would have done with the results of anonymous function
anonymousFunctionResults...
}
});
If I understood your question well :)
I have a requirement where I get the anchor tags id and based on the id I determine which function to execute.. so is there anything that suites below code
function treeItemClickHandler(id)
{
a=findDisplay(id);
a();
}
You can assign a function to a variable like so:
You can also return a function pointer from a function - see the return statement of findDisplay(id).
function treeItemClickHandler(id)
{
var a= findDisplay;
var other = a(id);
other();
}
function findDisplay(id)
{
return someOtherThing;
}
function someOtherThing()
{
}
Sure, functions are first class objects in JavaScript. For example, you can create a map (an object) which holds references to the functions you want to call:
var funcs = {
'id1': function(){...},
'id2': function(){...},
...
};
function treeItemClickHandler(id) {
if(id in funcs) {
funcs[id]();
}
}
As functions are treated as any other value, you can also return them from another function:
function findDisplay(id) {
// whatever logic here
var func = function() {};
return func;
}
functions are normal javascript values, so you can pass them around, (re)assign them to variables and use them as parameter values or return values for functions. Just use them ;) Your code is correct so far.
You can map between ids and functions to call in a number of ways.
One of the simpler ones is to create an object mapping ids to functions, and find the function to call from that object (this is in essence a nicer-looking switch statement).
Example:
function treeItemClickHandler(id)
{
var idMap = {
"some-id": findDisplay,
"another-id": doSomethingElse
};
if (!idMap.hasOwnProperty(id)) {
alert("Unknown id -- how to handle it?");
return;
}
// Call the corresponding function, passing the id
// This is necessary if multiple ids get handled by the same func
(idMap[id])(id);
}
function findDisplay(id)
{
// ...
}
function doSomethingElse(id)
{
// ...
}