Javascript operator && alternative option(required for limitation) [closed] - javascript

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How I can write the following without &&?
if(a == 1 && b == 2) { ... }
Can I create a function for the operator?

Create a function to encapsulate your operation:
function compare(a, b, value1, value2) {
if(a === value1) {
if(b === value2) {
return true;
}
}
return false;
}
And you can use it like so:
if(compare(a, b, 1, 2)) {
// Your action..
}

You can do this like
if(a==1){
if(b==2){
JS function
}
}
Both will work the same but if(a==1 && b==2) is a good approach to do exactly the same.

Not sure why you'd want to do this, but you could nest if statements:
if(a == 1){
if(b == 2){
...
}
}
Or you could use a bitwise operator, if you really just need to consider 2 and 1
if(b >> a === 1){
...
}
There are a lot ways to do it, but it really depends on your data.

You could take advantage of prototypal inheritance, and create a constructor with its prototype extended with methods.
function Comparer(a, b) {
if (!(this instanceof Comparer))
return new Comparer(a, b);
this.assign(a, b);
this.compare();
}
Comparer.prototype.result = false;
Comparer.prototype.compare = function() {
this.result = this.a == this.b;
};
Comparer.prototype.assign = function(a, b) {
this.a = a;
this.b = b;
};
Comparer.prototype.and = function(a, b) {
this.assign(a, b);
if (this.result !== false)
this.compare();
return this;
};
Comparer.prototype.or = function(a, b) {
this.assign(a, b);
if (this.result !== true)
this.compare();
return this;
};
And use it like this:
var a = 1,
b = 2;
if (Comparer(a, 1).and(b, 2).result)
console.log("pass");
else
console.log("fail");
We could even extend it to get rid of the if statement.
Comparer.prototype.then = function(fn) {
if (this.result === true)
fn();
return this;
};
Comparer.prototype.otherwise = function(fn) {
if (this.result === false)
fn();
return this;
};
And use it like this:
var a = 1,
b = 2;
Comparer(a, 1)
.and(b, 2)
.then(function() { console.log("pass"); })
.otherwise(function() { console.log("fail"); });
Or shorten things up like this:
var log = Function.bind.bind(console.log, console);
var a = 1,
b = 2;
Comparer(a, 1)
.and(b, 2)
.then(log("pass"))
.otherwise(log("fail"));

Your question is sort of pointless, but you could use the multiplication operator * instead of &&:
if(a==1 * b==2){
//do something
}

If you want to implement the operator && as a function, it's going to get ugly, because you need to pass the conditions as closures, whenever you care about short-circuiting with side-effects.
Example:
if(condition && changeTheWorld()) { ... }
// Cannot be translated into a function call of this nature:
if(land(condition, changeTheWorld()) { ... }
Instead, you would need to create a closure:
if(land(condition, function() {return changeTheWorld()}) {...}
As you can see, it's really cumbersome and verbose while there's no advantage.
If you really need this as a funciton, here is an
Implementation with short-circuiting
This function emulates the semantics of && correctly, if you pass the conditions that must not get evaluated—in the case of short-circuiting—as functions instead as expressions.
In other words, the function goes through the arguments in order, if one is a function, it evaluates it first, otherwise it just takes its value, if falsy, it aborts by returning false, otherwise, it continues with the next parameter.
function land(){
for(var i = 0; i < arguments.length; i++) {
var operand = arguments[i];
var value = (typeof operand === 'function') ? operand() : operand;
if (!value) {
return false;
}
}
return true;
}
Example:
function evaluateTo(result) {
return function() {
console.log("Evaluating " + result);
return result;
};
}
if(land(true, evaluateTo(1))) {
console.log("All truthy");
}
// Outputs:
// Evaluating 1
// All truthy
if(land(evaluateTo(1), evaluateTo(0), evaluateTo(true))) {
console.log("All truthy");
}
// Outputs:
// Evaluating 1
// Evaluating 0
Obligatory missile example
function changeTheWorld() {
console.log("Missiles away!");
// Firing 3 missiles
return nukeTheGlobe(3);
}
if(false && changeTheWorld() == 3) { ... }
// we survived, missiles not fired
if(naiveLand(maybe, changeTheWorld() == 3) { ... }
// Missiles away! no matter what value `maybe` has
if(land(false, function(){ return changeTheWorld() == 3; })) {...}
// we survived, missiles not fired

Related

Arguments Optional - why do I get a string for arguments (2)([3])?

This is a follow up to my questions on the Arguments Optional Challenge in Freecodecamp (see below0:
I have now satisfied 5/6 conditions of the challenge, except for when the input is addTogether(2,([3])), which returns '23' as a string instead of the correct 'undefined'.
If the [3] is an array, and an array is an object, shouldn't my checkNum function work to label that as undefined? Where was the string generated?
my code now:
function addTogether() {
function checkNum(x) {
return typeof x === 'number' ? x : undefined;
}
let num1 = checkNum(arguments[0]);
let num2 = checkNum(arguments[1]);
if (arguments.length === 1) {
if (typeof num1 === 'number') {
let a = num1;
return function (b) {
return a + b;
};
}
return undefined;
}
if (arguments.length > 1) {
if (typeof num1 !== 'number' || typeof num2 !== 'number') {
return undefined;
}
if (typeof num1 === 'number' && typeof num2 === 'number');
{
return arguments[0] + arguments[1];
}
}
}
THANKS
//original question below:
I am stuck on the freecodecamp problem Arguments Optional.
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional
In researching the problem, there have been multiple references to the following code-block, but I just can't get my head around what it means:
if(arguments.length==1){
if (typeof a == "number"){
return function(b){
if (typeof b == "number"){
return a + b;
}
};
}
}
I understand up to the 'return function(b)' part, then my brain melts.
If someone could please explain it as if to a 6-year-old, this noob would really appreciate the help.
This is quite common practice to return a function instead of a value.
When the outer function (which is supposed to do addition) is called with one argument, instead of doing addition (can't do) it is returning a function. When that function is called subsequently with a number parameter it executes the function b and does the sum.
Let us say the outer function name is add() so it can be triggered the following ways:
add(10, 15); // 25
var f = add(20);
f(18) // 38
add(4)(6) // 10
Full example:
function add(a, b) {
if (arguments.length == 1) {
if (typeof a == "number") {
return function (b) {
if (typeof b == "number") {
return a + b;
}
};
} else {
return "undefined";
}
} else if (arguments.length == 2) {
if (typeof a == "number" && typeof b == "number") {
return a + b;
} else {
return "undefined";
}
} else {
return "undefined";
}
}
console.log(add(10, 15));
var f = add(20);
console.log(f(18));
console.log(add("xyz"));
console.log(add(10, "5"));
console.log(add(4)(6));
We can declare functions in 2 ways, the regular way:
function test(){
}
or the interesting way
let test = function(){
}
in this case, the function is returning a function
see here:
function returnfunction(){
return function(b){
if (typeof b == "number"){
return a + b;
}
}
}
let x = returnfunction()
So, x is the return value of returnfunction, which is
function(b){
if (typeof b == "number"){
return a + b;
}
}
So similar to above,
x = function(){
//...
}

My javascript Program comparing 2 numbers keeps returning error

I am trying to write a function that takes 2 numbers and returns the bigger one but I keep getting error module.js540 throw err.
function largerThan(a,b){
if(a > b) {
return a;
}else {
return b;
}
}
var biggerNumber = largerThan(1,2);
console.log(biggerNumber)
return var biggerNumber = a is a syntax error
You're looking for:
return a
function largerThan(a,b){
if(a > b) {
return a;
}else {
return b
}
}
var biggerNumber = largerThan(1,2);
console.log(biggerNumber)
try this
You are mixing a 'variable declaration' statement and a 'return' statement.
The code should look like this:
function largerThan(a,b) {
if(a > b) {
return a;
}else {
return b;
}
}
var biggerNumber = largerThan(1,2);
If b is the larger number, then the function will return the value in b. The statement "var biggerNumber = largerThan(1,2)" will store the value that the function returned to your variable.

closure in javascript with multiple empty calls to sum function

I faced this question in one interview. I did not get how to solve this.
Question: Write a sum function which will add 2 numbers, but numbers can be passed to a function in following ways:
sum(3)(4) // answer should be 7
sum(3)()(4)//answer should be 7
sum(3)()()()()(4) //answer should b 7
I can solve first function using closure, in fact for the second function also I can check the arguments and if arguments length is zero I can again make a call to sum to except next parameter.
But how to make it generic ? Means even your first parameter and last parameter has 'N' number of calls & those can be empty or parameterized, it should return sum.
Recorded a video how to solve it:
https://youtu.be/7hnYMIOVEg0
Text answer:
function sum(numberOne) {
return function innerSum(numberTwo) {
if (typeof(numberTwo) === 'number') {
return numberOne + numberTwo;
}
return innerSum;
}
}
Output:
sum(3)(4); => 7
sum(5)()()(10); => 15
Basically, you need to return inner function (innerSum) up until you receive a value - then you return number.
You could also choose another name - like _sum(), or addToFirstNumber() for your method.
You can always return a function from within a function:
let a;
function sum(value) {
if (typeof value !== "number") {
return sum;
}
if (typeof a !== "number") {
a = value;
return sum;
}
let result = a + value;
a = null;
return result;
}
see https://jsfiddle.net/d9tLh11k/1/
function sum(num1) {
return function sum2(num2) {
if(num2 === undefined) {
return sum2;
}
return num1 + num2;
}
}
console.log(sum(4)()()()(3)); // -> 7
Or in ES6:
const add = num1 => num2 => num2 === undefined ? add(num1) : num1 + num2;
console.log(add(4)()()()()()(3)); // -> 7
function add (n) {
var func = function (x) {
if(typeof x==="undefined"){
x=0;
}
return add (n + x);
};
func.valueOf = func.toString = function () {
return n;
};
return func;
}
console.log(+add(1)(2)(3)()()(6));
I have already given answer of this question Here
but according to your question I have modified that
function add (n) {
var func = function (x) {
if(typeof x==="undefined"){
x=0;
}
return add (n + x);
};
func.valueOf = func.toString = function () {
return n;
};
return func;
}
console.log(+add(1)(2)(3)()()(6));
Run code like that
console.log(+add(1)(2)(3)()()(6));
This should do it
function sum(num1) {
if (arguments.length === 0){
return sum;
}
return function innerSum(num2) {
if (arguments.length > 0){
return num1 + num2;
}else{
return innerSum;
}
}
}
You can do this in a number of ways, but mostly you'll want named recursion. That is, you can have something like:
sum = start => (...args) => args.length? args[0] + start : sum(start)
but it might look cleaner to write this as:
function sum(start) {
function out(...args) {
return args.length? start + args[0] : out
}
return out;
}

I cannot return the real variable on processed recursion?

I have been doing this recursion in javascript; however I cannot return the real value of x on return. Instead, it is returning the processed value. The code is doing it's job but it's returning the processed variable on recursion. I tried to store the variable on x, but I still fail.
I want to return the last call stack to get the real variable.
This code returns 0 is Even, 1 is Even - how can the code be changed such that these cases would work as expected?
function isEven(x) {
var y =x;
if (x<0) {
x = x * -1;
}
if ( x===0 ) {
return console.log(y+' is Even');
} else if( x===1 ) {
return console.log(y+' is Odd');
} else {
return isEven(x-2);
}
// →
console.log(isEven(10));
console.log(isEven(-11));
}
You cannot access the initial value using your code.
The simplest way to achieve this goal is to add a function parameter, which will store the original value:
function isEven(x, initial) {
initial = initial || x; // so that isEven(10) => isEven(10, 10)
if (x<0) {
x = x * -1;
}
if(x===0) {
return initial+' is Even';
} else if(x===1) {
return initial+' is Odd';
} else
return isEven(x-2, initial);
}
// →
console.log(isEven(10));
console.log(isEven(-11));
However, the correct solution is to separate the initial call and recursive calls. For example, it can be achieved using nested functions.
It is also a good idea to abstract logics (boolean) and displayed information (string).
function isEvenString(initial) {
function isEvenBool(x) {
if (x < 0) {
x = x * -1;
}
if (x === 0) {
return true;
}
if (x === 1) {
return false;
}
return isEvenBool(x - 2);
}
return initial + (isEvenBool(initial) ? " is Even" : " is Odd");
}
// →
console.log(isEvenString(10));
console.log(isEvenString(-11));
P.S. Note that this isEven function is good for education purposes, but absolutely useless in practice. It takes 1 000 000 function calls to determine that 2 000 000 is even whilst it can be done using one line of code in O(1) operations:
function isEvenString(x) {
return x % 2 === 0;
}
I assume what you're trying to do is print the original value that was given, not the final value from the recursion. But you're reassigning y every time you recurse, so it doesn't contain the original value.
One solution is to split the function up into a main function and a recursive internal function.
function isEven(x) {
var y =x;
function isEvenRecurse(x) {
if (x<0) {
x = x * -1;
}
if(x===0) {
return y+' is Even';
} else if(x===1) {
return y+' is Odd';
} else {
return isEvenRecurse(x-2);
}
}
isEvenRecurse(y);
}
Another way is to pass an extra argument to the function when recursing.
function isEven(x, y) {
if (arguments.length == 1) {
y = x;
}
if (x<0) {
x = x * -1;
}
if(x===0) {
return y+' is Even';
} else if(x===1) {
return y+' is Odd';
} else {
return isEven(x-2, y);
}
}

Javascript functional programming quiz

Here is the problem. I have to implement make function:
var sum = function (a, b) { return a + b; }
var mult = function (a, b) { return a * b; }
//'make' function goes here
var res = make(1)(2)(3)(4);
console.log(res(sum)); //OUTPUT: 10
console.log(res(mult)); //OUTPUT: 24
I have implemented it, but I feel like a little better way still exists. :)
So, here is my solution:
function make(a, arr) {
if (a instanceof Function) { return arr.reduce(a); }
arr = arr || [];
arr.push(a);
return function (b) { return make(b, arr); };
}
You want functions? You can have functions!
function sum(a, b) { return a + b; }
function mult(a, b) { return a * b; }
function diff(a, b) { return a - b; }
function make(x, f) {
if (typeof x === 'function') return f(x);
return function(y) {
return make(y, function(a) {
return f ? a(f(a), x) : x;
});
};
}
console.log(make(1)(2)(3)(4)(sum)); // -> 10
console.log(make(1)(2)(3)(4)(mult)); // -> 24
console.log(make(4)(3)(2)(1)(diff)); // -> -2
Instead of building up an array, this builds up a function that, when given a function, reduces all the elements using that function, from left to right :)
I'm pretty sure this wouldn't qualify as code that anyone would ever want to see in their codebase.
function make(inp, arr) {
if (typeof inp == 'function') {
while(arr.length > 1)
arr.push(inp(arr.pop(), arr.pop()));
return arr[0];
}
if (!arr) arr = [];
arr.push(inp);
return function (inp1) {
return make(inp1, arr);
};
}
Here's a better JavaScript specific solution:
var test = make(1)(2)(3)(4);
alert(test(add)); // ((1 + 2) + 3) + 4 = 10
alert(test(mul)); // ((1 * 2) * 3) * 4 = 24
alert(test(sub)); // ((1 - 2) - 3) - 4 = -8
function make(x) {
if (typeof x !== "function") return foldl([x]);
throw new TypeError("Initial value can't be a function");
}
function foldl(array) {
return function (fx) {
return typeof fx !== "function" ?
foldl(array.concat(fx)) :
array.reduce(fx);
};
}
function add(a, b) { return a + b; }
function mul(a, b) { return a * b; }
function sub(a, b) { return a - b; }
There are several advantages to this method:
Better error reporting when you write incorrect code like make(add).
Simple functional definition which is easy to read and understand.
If you want foldr then just rename reduce to reduceRight.
Using concat instead of push to preserve original array.
I can't think of a better functional implementation for make.

Categories

Resources