Javascript: Pass Hash Key as Parameter - javascript

I have a hash called 'tag' with several keys, including width, height, x, and y. I also have this function:
function invertCoordinates(measure, coordinate){
tag.measure = tag.measure * -1;
tag.coordinate = tag.coordinate - tag.measure;
}
In which I want to pass tag's keys:
invertCoordinates(width, x);
or
invertCoordinates(height, y);
Unfortunately, I can't pass keys in this manner. Is there some other way to accomplish this?

Can you do:
function invertCoordinates(measure, coordinate){
tag[measure] = tag[measure] * -1;
tag[coordinate] = tag[coordinate] - tag[measure];
}
where measure and coordinate are strings? For instance:
invertCoordinates("width", "x");

Use the array-access notation (tag[measure]) and pass the keys as strings: invertCoordinates('width', 'x')

Related

Supporting arrays in custom functions with multiple inputs

I have a custom function in my google apps script that takes two variables. I want this function to take two arrays for parameters, but the standard approach of putting "if input.map, return input.map(function)" doesn't work with two variables.
I have tried recursing through the inputs, but since there are two in the function, it does not work with both.
this is not the function i am using, but it has the same problem.
function multiply(x,y)
{
if (x.map){
return x.map(multiply)
}
if (y.map){
return y.map(multiply)
}
return x * y
}
I expect the formula to take two arrays (i.e. A1:A5, B1:B5) and perform the function on each variable -- i.e. returning A1 * B1, A2 * B2 etc.
Issue:
multiply receives two arguments. When multiply is provided as a function argument to Array.map, the first argument will be the element of the array on which map is called and the second argument will be the element's index.
Solution:
Use map only on the first array x and then use elements from the corresponding second array y
Snippet:
function multiply(x, y) {
if (x.map) {
return x.map(function(xEl, i) {
yEl = y.map ? y[i] : y; // corresponding y Element
return multiply(xEl, yEl);
});
}
if (y.map) {//used, when y is a array and x is number
return multiply(y, x);
}
return x * y;// default
}
a = [[1],[2]];
b= [[3],[4]];
c= [[5,6],[7,8]];
d= [[1,2],[3,4]];
console.log(JSON.stringify(multiply(a,b)));
console.log(JSON.stringify(multiply(a,5)));
console.log(JSON.stringify(multiply(5,b)));
console.log(JSON.stringify(multiply(c,d)));
console.log(JSON.stringify(multiply(c,2)));
console.log(JSON.stringify(multiply(a,c))); //trims c
console.log(JSON.stringify(multiply(c,a)));//throws error
References:
Array#map

Value for optional parameter by name (Javascript)

I have a javascript function like this
function drawImageOnCanvas(canvas, texturePath, color, type, onCall, modelPath, scene, pX, pY, pZ, scale, transform) {}
Here onCall, modelPath, scene, pX, pY, pZ, scale, transform are optional parameters. How can i pass value only for scale. Is there any way to define parameter name and pass value?
You can use an object as the function's parameter.
function drawImageOnCanvas(canvas, options){
var scale = options.scale;
}
And in call site:
drawImageOnCanvas(canvas, {scale: 2});
Also to handle optional parameters, you can check their existence using an if or || or ?:.
var color = /*default color*/;
if (options.color){
color = options.color;
}
Or
var color = options.color || /*default color*/;
Or
var color = options.color ? options.color : /*default color*/;
Note: If options contains parameters having false, 0, etc values then the methods above are not suitable anymore. For example, assume we have a parameter called isActive, then passing {isActive: false} will lead to the /*default isActive*/. To address this problem, you can use .hasOwnProperty or in.
var options = {scale: 2, isActive: false};
console.log('isActive' in options); // true
console.log(options.hasOwnProperty('isActive')); // true
console.log(options.isActive); // false
Anytime you have a function with many optional parameters, a much better option is to use a single parameter for all the optional parameters as an object.
In ES6, this case be more easily accomplished using destructuring and default parameters.
function drawImageOnCanvas(canvas, {scale = 1} = {}) {
...
}
Then you can call the function like this:
drawImageOnCanvas(canvas, { scale: 2 });
function test({ x = 10 } = {}) {
console.log(x);
}
test({ x: 100 }); // passing x
test({ y: 200 }); // not passing x
test(); // not passing anything still works
You create an array having .length equal to the number of expected parameters to function, set parameters passed to function as elements of an array, set index 10 of array to value for scale, use rest element to pass array of parameters to function, destructuring assignment within function to define named variables
function drawImageOnCanvas(canvas, texturePath, color, type, onCall
, modelPath, scene, pX, pY, pZ, scale, transform) {
console.log(canvas, texturePath, color, type, scale);
}
var args = Array.of(document.createElement("canvas"), 1, 2, 3, ...Array(7));
args[10] = {scale:456};
drawImageOnCanvas(...args);

Unfamiliar use of square brackets in calling a function

In the middle of this page, I find the code below.
var plus = function(x,y){ return x + y };
var minus = function(x,y){ return x - y };
var operations = {
'+': plus,
'-': minus
};
var calculate = function(x, y, operation){
return operations[operation](x, y);
}
calculate(38, 4, '+');
calculate(47, 3, '-');
Now while I can trace how it works, I've never seen this use of square brackets before. It certainly doesn't look like it's creating an array or referencing a member of an array. Is this common? If so, where are some other examples?
It is a dictionary access, which is like an array, but with a key instead of a numeric index.
operations['+'] will evaluate to the function plus, which is then called with the arguments plus(x,y).
It's called bracket notation.
In JavaScript you can use it to access object properties.
here operations is an object where the symbols + and - refers to two functions.
operations[operation] will return a reference to function plus where value of operation is + and then the following () will invoke the function
operations is an object and when you do operations[property] you will get the associated function and then you are passing the operands as x and y.
operations['+'] is function (x,y){ return x + y } which is plus
operations['-'] is function (x,y){ return x - y } which is minus
My JavaScript book says that object properties need be named with arbitrary names. But '+' and '-' are not names. From the original question, it is inferred that object properties just need be keyed, not named.

Using Strings as KEY of map in javascript

Im using this 'map' on js:
var myMap = new Object();
myMap[key1]=value1; //like this n times...
but i want to use the key as some combination of two strings meaning:
function getMapValue(str1,str2){...}
i dont mind joining the two strings into one long string and use the function with the long string
any ideas?
You can make a map of maps (just be sure to check that the intermediate map exists when accessing it)
var myMap = {}; //dont use "new Object()". It is evil.
function insert(k1, k2, v){
if(!(k1 in myMap)){ myMap[k1] = {}; }
myMap[k1][k2] = v;
}
function get(k1, k2){
return myMap[k1] && myMap[k1][k2];
}
And if you want to join two substrings into a single one you can use the plus operator to concatenate things.
var customKey = k1 + '|' + k2;
Just be sure your separator can't be used in a normal key to avoid conflicts.
If I got you right, the following should help:
var myMap = {"key1" : "something1", "key2" : "something2"};
to get value for a key, you you use, either: return myMap.key1;
Or: return myMap.["key1"];
If you had/did: myMap["key1key2"] = "MagicHappens!";
you could use myMap.key1key2 to get the value or myMap["key1key2"], or even: return myMap["key1"+"key2"];
Or:
var x = "key1";
var y = "key2";
return myMap[x+y];
in your getter function, you get the two variables for the keys which you can then directly use.

Javascript: passing multiple arguments as a single variable

is it possible to pass multiple arguments using a single variable? For example, if I wanted to do something like:
function foo(x,y){
document.write("X is " + x);
document.write("Y is " + y);
}
var bar = "0,10";
foo(bar);
The example above is an simplified example of what I was trying to do. It doesn't work (because the "bar" is detected as a single argument). I know that there are easier ways to implement this using arrays.
So, I ask this question mostly out of curiosity - is it possible to get the "bar" variable to be detected as not one, but 2 arguments?
Thanks!
function foo(thing) {
document.write("X is " + thing.x);
document.write("Y is " + thing.y);
}
var bar = {x:0, y:10};
foo(bar);
What you're asking for is impossible. If you want to pass multiple values in a single argument, use an Array or an Object. If you really must use a string, you'll have to call split() to break the argument string into an array.
function Add (a, b, c) {
return a + b + c;
}
var nums = [1, 2, 4];
var sum = Add.apply (null, nums);
variable-length argument list:
function Add () {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
var n = Add (1, 2, 3, 4, 5);
Reference: apply method (Function object)
Sure, this is common to pass an object for options
function foo(options){
//...
}
then you can pass in anything...
var opts = {};//create an object
opts['x'] = 5;//set whatever properties you want
opts['y'] = 23;
opts['border'] = 3;
foo(opts);//pass 1 argument, with as many values as you want
Often these are defined inline, especially if the values are not needed outside of the method call.
foo({'x':5,'y':23,'border':3});
Not really.
You could do:
window.foo.apply(window, bar.split(','));
(Apply lets you pass an array of arguments instead of each argument separately)
… but the phrase "ugly" comes to mind.
You may use this:
var bar = [0,10]; // creates an array
foo(bar);
function foo(arg){
document.write("X is " + arg[0]);
document.write("Y is " + arg[1]);
}
No, but you could pass a an array or object:
function foo(options){
document.write("X is " + options.x);
document.write("Y is " + options.y);
}
var bar = {x: 0, y:10};
No, it's not possible. You could put two arguments in an array, but an array is still one variable. Then you would need to rewrite the function to accept one variable, and treat it as an array, like this:
function foo(x){
document.write("X is " + x[0]);
document.write("Y is " + x[1]);
}
Basically, a function accepts variables as arguments and, no matter what kind of variable you pass it, each variable is still only one variable - there's no way to get a single variable to be recognized as multiple arguments. An array is one variable, a JSON object is one variable, etc. These things have multiple parts to them, but they're encapsulated by a single variable.
How about? (For ES6+)
function foo({x, y}){
document.write("X is " + x);
document.write("Y is " + y);
}
and call it with:
foo({x:10, y:5})
There is a downside to using a single structured argument over multiple arguments, and that is with multiple arguments you can use /** in may IDEs to generate a method header which will display an #param for each argument.
But if you only have one argument then you will lose the niceness of a description for each argument and hence less useful intelli-sense in the IDE as it wont pick up the docuemntation of the structure's properties.
/**
* Do stuff
* #param {*} param0 - A structure containing the blah, blah blah data
*/
function foo({x, y}){
instead of..
/**
*
* #param {*} x - The value for blah
* #param {*} y - the value for blah-blah
*/
foo1(x, y){
To directly answer your question, no. It's worth noting that the way you have bar defined it's only one value, a string containing "0,10".
function myFunction(a,b){
//do stuff with a and b here
}
myFunction(1,'text')
or...
<a onClick="myFunction(1,'text');"
There's an article on the issue here.

Categories

Resources