multiple actions within short hand javascript - javascript

Hi I am wondering if there is a good way to run multiple functions or methods if a condition is met within short-hand javascript.
I have tried this, but doesn't work:
!gameView?launchFull(); alert('action 2'):returnView();

Can you do it? Yes.
Working example
var x = true;
!x?(alert('true 1'),alert('true 2')):(alert('false 1'),alert('false 2'));
Note brackets around the sections.
But, should you do it? no.

if there is a good way
No.
The ternary operator is a good way to do a simple "If A x = y ELSE x = z". Trying to go beyond that is a good way to create an unreadable mess.
Use a proper if { } else { }.
Readability is far more valuable then shortness.

you can do like this.
function m() {alert("i am M");}
function k() {alert("i am K");}
function l() {alert("i am L");}
m.call();
var func = 1===1 ? l : k;
func.call();
Func will work as a delegate and when the call is made it will have a function associated with the variable

Related

for loop calculation syntax within a function is not correct

what is the actual syntax for the for loop?
what I want to do is to calculate 2 number variables inside a function using a for a loop.
I am going over and over the internet and I cannot find anything that can help me specifically for this task I was given to do.
I am not looking for the answers, just for a guideline or a hint.
or just give me the syntax and I will try my best to adjust it to my needs.
just so you have a better understanding of the task, here it is.
Features
Instead of hardcoding Y (the result of the Fibonacci of X), calculate it with a for loop
The calculation should be wrapped in a function, that gets X as an argument, and returns Y
After the function, you should call the function, and assign the returned value in your HTML to present to the user
btw, i know that i did not put the innerHTML correcly, and also i did not do the syntax right, this is actually what i am asking here.
thank you!!
i have tried this:
var answer = document.getElementsByClassName("paragraph")
function calc (x){
for (let a = 2; a <= x; a++){
answer = document.textContent("this is a pr")
}
return calc
}
calc(2)
You should avoid to use classname, instead use .querySelectorAll
You don't need to specify how many answer exists if your calc() is just 2.
let answer = document.querySelectorAll(".paragraph");
function calc(x) {
for (let a = 0; a <= x; a++) {
answer[a].innerText = "this is a pr";
}
}
calc(2);
<p class="paragraph">A</p>
<p class="paragraph">B</p>
<p class="paragraph">C</p>
<p class="paragraph">D</p>
<p class="paragraph">E</p>
I don't know if this is what you're searching for but it's this is the standard for loop function to achieve these types of result.
function calc(x){
let sum = 0;
for (let a=0; a<x; a++){
sum+=a;
}
return sum;
}
console.log(calc(5));
The Syntax of the loop in your code is correct, the thing is that you cannot return your function inside itself without calling it as you have done in your code.
'return calc' is wrong. You should use 'return calc(argument-Variable or value)' as you have a parameter passed in your function, but this should only be used if you are writing a code of recursion. If not you should return a variable.
Refer to the code below for further clarifications

JavaScript challenge

So I have a small JavaScript function that I need to figure out how to code, as a challenge. Basically:
function me() { // imp this function code }
var isSame1 = me("123")("321") === "123 321";
var isSame2 = me("321")("123") === "321 123";
Desired output is we want both isSame vars to be true. So from what I understand thus far, the me() function needs to return a function initially (some form of recursion I'd imagine) and then somehow a string in order to concat the resulting strings (the real example has some string manipulation during the me() function but I don't need help with that part).
I feel like there is a JavaScript feature that I am not seeing clearly here. I am aware that I can return a function as an object and call it, which is a really neat feature, but the string handling/passing to the other function and then returning it in the end is what is confusing me.
Can anyone point me in the right direction for what to look up. Don't want it to be answered completely for me, just want to be given the right research area.
Gerneio
Currying in JavaScript is quite easy. Just return a scoped function from me().
For example, to implement curried addition using a closure, you could write a function like this:
function add (a) {
return b => a + b
}
console.log(add(3)(4))
Or see below for the solution to the challenge.
Spoiler (full implementation):
function me (a) {
return b => `${a} ${b}`
}
console.log(me(123)(321))
console.log(me(321)(123))
Hope this helps you find what you're looking for.

A smarter inline than ternary for dealing with undefined objects

This is a question asking if such a technique exists..
I am looking for a way in general to do an inline statement that performs an action if the item object is defined else does nothing (so instead of (condition)?if:else; it is just (condition)?if;)
(item)?[item.member='foo']:0; //ReferenceError: item is not defined
var item={'member':'bar'};//item could be an object but it wasn't defined
I would have thought that there was a way beside 'try catch error'
for a hypothetical (somewhat impractical but best that I could think of) example
In the following snippet there might be lots of code surrounding the lines and many things going on. Is there a neat way to say only draw if the pen is defined as sometimes-but-not-always there is to be drawing done, sometimes no drawing - only the surrounding calculations instead. So the canvas is not always in use
//calculations and code
if(drawing===true){
var pen=document.getElementById('canvas');
pen=pen.getContext("2d");
//other canvas setup stuff
}
//calculations and code
pen.moveTo(0,0);
pen.lineTo(10,10);
the last two lines it would be great if there was some trick in JavaScript to do something like (pseudo code):
(pen) ? pen.lineTo(10,10);
This would throw unexpected ; error!
Is there a different kind of inline other than ternary and a way to return if the object is undefined?
There are two that I know of:
// Set a variable if not set
var x = x || 'hi';
// Do something if x is truthy
// Needs a scope, may not always be "this."
this.x && console.log(this.x);
So in your example, if pen is global, you can do window.pen && pen.lineTo(10, 10);
There's also the very simple one-line if:
if (pen) pen.lineTo(10, 10);
which technically isn't shorthand of any kind, it's just short. Compare the two line lengths (your pseudo-code versus this method):
(pen) ? pen.lineTo(10,10);
if (pen) pen.lineTo(10, 10);
Getting a bit more in-depth, I'd recommend against something like
if (pen) pen.moveTo(0, 0);
if (pen) pen.lineTo(10, 10);
because yes it's a couple of one-liners but you're doubling up logic, repeating yourself and you'll make people think "why did he do that?". In that situation, I'd just keep it simple:
if (pen) {
pen.moveTo(0, 0);
pen.lineTo(10, 10);
}
Yes, hoewever, you need to declare the variable somehow, e.g.:
// declare pen
var pen;
//calculations and code
if(drawing===true){
pen=document.getElementById('canvas');
pen=pen.getContext("2d");
//other canvas setup stuff
}
//calculations and code
pen && pen.moveTo(0,0);
pen && pen.lineTo(10,10);
//var pen; not declared
(!window.pen)&&console.log('no pen');
(window.pen)&&console.log('is pen');
this will print 'no pen' and will not throw error
var pen=document.getElementById('canvas');
pen=pen.getContext("2d");
(window.pen)&&pen.lineTo(10,10);
or if you don't use words reserved in jquery
$.pen=$('#canvas')[0];
pen=pen.getContext("2d");
($.pen)&&pen.lineTo(10,10);
Do a bunch of things in order:
($.pen)&&[
pen.lineTo(10,10),
pen.lineTo(20,20),
pen.lineTo(30,30)];

Javascript: var = var = function

I'm sure this thing is duplicated somewhere but I don't know what to search.
So, I've been looking through a Node.JS Application and found this code and wondered what it does. I have tried searching but I don't know what to search so I was hoping someone would it explain it to me.
init = refresh = function () {
// code here..
};
I understand 1 equals, but why 2? does it make some sort of alias so that function can be run with both init and refresh?
= resolves the right hand side and then assigns the result to the left hand side.
The result of doing this is the same as the result assigned.
So that assigns the function to both init and refresh
Quentin did a very good job telling you what it is doing.
I just wanted to chime in to give an example where you might use this:
Say for instance you have an object:
var obj = {
init: function() {
var x = this.x = [1,2,3];
}
};
What this allows you to do is reference your x variable two different ways (either through x or this.x).
Now why would you do this?
Well two major reasons.
It is faster to access x rather than this.x (but you still need to access it elsewhere)
It produces easier to read code when having to read/write to x lots of times in one function.
This is just another reason why you would use it.
But in most cases it is just aliases, such as: forEach -> each
Here's an explanation using operator associativity and precedence.
So, looking at an operator precedence description from Mozilla, when an expression includes multiple operators of the same precedence, as in
a OP b OP c
, then you check whether that level of precedence uses right-to-left or left-to-right associativity.
a = b = c
The assignment operator in JavaScript is the only operator on its level of precedence.
It has right-to-left associativity
So in a = b = c, b = c is evaluated first, assigning the value of c to b.
Then the expression becomes a = b.

In Javascript, what's better than try/catch for exiting an outer scope?

In Javascript, I sometimes want to return a value from a scope that isn't the current function. It might be a block of code within the function, or it might be an enclosing function as in the following example, which uses a local function to recursively search for something. As soon as it finds a solution, the search is done and the outer function should just exit. Unfortunately, I can't think of a simpler way to do this than by hacking try/catch for the purpose:
function solve(searchSpace) {
var search = function (stuff) {
var solution = isItSolved(stuff);
if (solution) {
throw solution;
} else {
search(narrowThisWay(stuff));
search(narrowThatWay(stuff));
};
};
try {
return search(searchSpace);
} catch (solution) {
return solution;
};
};
I realize one could assign the solution to a local variable and then check it before making another recursive call, but my question is specifically about transfer of control. Is there a better way than the above? Perhaps involving label/break?
Edit: since the answers to date are variations of "ew that's bad
you're not supposed to do that", let me add some necessary
context. I'm hacking on an open-source compiler that targets
Javascript. No one is going to write this code by hand, so please
don't tell me "this is a bad programming technique". What I want is a
better code generation technique. The question is whether anyone has
any clever hack for exploiting Javascript to get more flexible control
transfer.
The reason assigning the result to a local variable and checking it is
ruled out is because that requires understanding the code in a way
that is hard for a compiler to do.
It seems I stand corrected on the intent of the question. If statements are are a useful and readable way to structure code and make it flow however you want to. There's a reason goto was taken out of so many languages, because you don't need it. And it seems like, based on your example code, you're using a try-catch block as a form of goto. If you don't want certain things to run then use if statements or equivalents:
function solve(searchSpace) {
function search = function (stuff) {
//|| will only return the first value if that value is truthy, subsequent values will be ignored
return isItSolved(stuff) || (search(narrowThisWay(stuff)) || search(narrowThatWay(stuff)));
};
return search(searchSpace);
};
I know of no way to break out of function calls like you want. You can break out of loops using labels, but it doesn't seem that's much help to your situation. Other than that, I don't think JavaScript has any such ability beyond your use of exceptions
function solve(stuff) {
return isItSolved(stuff) || solve(narrowThisWay(stuff)) || solve(narrowThatWay(stuff));
}
Bob's way is good... exept that he uses twice the function statement (and that he uses ; after a function delaration without an assignment)... and that as we can do it that way, function solve actually is function search.
PS : This code will epically fail if the isItSolved, narrowThisWay or narrowThatWay functions can return a value evaluated to false as a positive result. In this cas, you would have to use ? : statement in order to check if all responses are !== undefined.
PS2: And of ourse, if these function can send an error, you have to catch it...
It looks like you're doing a fairly straightforward recursive search in your example. Why not just use "return"?
function solve(searchSpace) {
var search = function (stuff) {
var solution = isItSolved(stuff);
if (solution) {
return solution;
} else {
solution = search(narrowThisWay(stuff));
if (solution) {
return solution;
}
return search(narrowThatWay(stuff));
};
};
return search(searchSpace);
};
I suppose it could be that there are other constraints you haven't mentioned, but it's in general possible to turn any control flow into a set of nested (or recursive) functions, with appropriate return values.
The cleanest way would be to use a continuation, but you don't have that efficiently in JS (a few JS engines support continuations, but for the rest there's only CPS, which cries out for tail calls). In C, you could use setjmp/longjmp. In Common Lisp, you could use conditions (which include the functionality of exceptions plus much more). In JS, exceptions are the only non-local control flow option you have available.
You can programmatically transform a program into another that uses CPS.
function solve(searchSpace, isItSolved, isBase, narrowThisWay, narrowThatWay) {
function search(stuff, k) {
solution = isItSolved(stuff);
if (solution) {
return solution;
} else if (isBase(stuff)) {
return k();
} else {
return search(narrowThisWay(stuff), function() {
return search(narrowThatWay(stuff), k);
});
};
};
return search(searchSpace, function(val) {return val});
};
var arr=[1, 2,9,72,0,34,5,33,24,62,89,90,30,54,590,23,59,62,73];
solve(arr, function(a) {return (a.length==1 && a[0] == 5) ? a[0] : false;},
function (a) {return a.length < 2; },
function (a) {return a.slice(0, a.length / 2);},
function (a) {return a.slice(a.length / 2);}
);

Categories