JavaScript function as argument of function on a variable? - javascript

Here's what I have:
function verificarNumero(test, num) {
return (test(num));
};
var resultadoTesteMultiplos = verificarNumero(function (num){return (num % 10 == 0);}, num1);
This function is supposed to find out if a number is a multiple of 10.
I know there are simpler ways to do it, but I really want to make this work.
I want to be able to do something like console.log(resultadoTesteMultiplos(10)); but the console returns "resultadoTesteMultiplos is not a function", and "num1 is undefined."
What am I doing wrong?

Sounds like you meant to curry but only got half way:
function verificarNumero(test) {
return function(num) {
return test(num);
};
}
var resultadoTesteMultiplos = verificarNumero(function(num) {
return (num % 10 == 0);
});
console.log(resultadoTesteMultiplos(10));

If you define num1 variable your code should work and the type of the resultadoTesteMultiplos is boolean. See the working snippet below please:
var num1 = 10;
function verificarNumero(test, num) {
return (test(num));
};
var resultadoTesteMultiplos = verificarNumero(function(num) {
return (num % 10 == 0);
}, num1);
console.log(typeof resultadoTesteMultiplos);
console.log(resultadoTesteMultiplos);

Return a function from verificarNumero, not the result of the function.
function verificarNumero (cb) {
return function (num) {
return cb.apply(this, [num]);
}
};
resultadoTesteMultiplos = verificarNumero(function (num) {
return (num % 10 == 0);
};
console.log(resultadoTesteMultiplos(10));

Related

Write code that uses an immediately-invoked function expression (IIFE) to create the fibonacci function where indicated

Currently, I am trying to write javascript to do a fibonacci sequence. I got the math part but we have to have an array named fibonacciResults and I am unsure on how to use an array named fibonacciResults and initialize it so that fibonacci(0) will be 0 and fibonacci(1) will be 1. Also, If the result (fibonacci(n)) has never been calculated before, calculate the new result recursively and save it in the fibonacciResults array.
document.querySelector('#calculate-fibonacci').addEventListener('click', function () {
var fibonacci; // Do not declare more variables here.
// WRITE YOUR fibonacci FUNCTION HERE
fibonacci = function fibonacci(n) {
fibonacciResults = [];
n = Math.round(n);
if (Number.isFinite(n) && n >= 0) {
if (n < 2) {
return n;
}
return fibonacci(n - 2) + fibonacci(n - 1);
}
return 0;
};
(function () {
var whichFibonacciNumber;
// Get the user's number.
whichFibonacciNumber = parseInt(document.querySelector('#fibonacci-input').value, 10);
// Use the fibonacci function to calculate the output.
document.querySelector('#which-fibonacci-number').textContent = whichFibonacciNumber;
document.querySelector('#fibonacci-number').textContent = fibonacci(whichFibonacciNumber);
}());
}, false);
fibonacci = (function () {
var cache = {};
return function (n) {
var cached = cache[n];
if (cached) return cached;
if (n <= 1) return n;
console.log(n);
return (cache[n] = fibonacci(n - 2) + fibonacci(n - 1));
};
}());

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;
}

trying to understand if/else loops combined with functions

so I am trying to create a function with two parameters. This function will be passed with two numbers as arguments. calculate the sum of the parameters. If the sum is less than or equal to 25, the function should return true. If not it should return false.
I know I must use a if and else loop to check the parameters (or a ternary which we have not covered yet.) This is what I have gotten so far. Please tell me if I am on the right track or completely wrong.
function sum(augment1,augment2) {
var num= augment1 + augment2;
return num;
}
var a=sum(10,30)
console.log(a);
if (num > 25) {
return true
}
else {
return false;
}
There's no reason to use an if-else statement - the <= operator returns a boolean result, so you could just return it:
function isSumEqualOrLessThan25(augment1, augment2) {
var sum = augment1 + augment2;
return sum <= 25;
}
Your conditions should be inside your function right? So if the sum is less than or equal to 25 return true else return false. Can you try following?
function sum(augment1, augment2) {
var num = augment1 + augment2;
if (num <= 25) {
return true
} else {
return false;
}
}
var a = sum(10, 30)
console.log(a); // should be false

passing variables from one function to the other in Javascript

I have a JavaScript program with 3 functions. The first 2 functions both have the variable values inside and I want to access those variables in the third function but i get an error which says the variables are undefined.
I tried setting the variables globally outside the function and then accessing them but been having the same errors.
var result;
var result2;
function getOpens(){
result = 10;
}
function getClicks(){
result2 = 6
}
function getTotal(){
if(result >= 10 && result2 < 1)
{
//DO SOMETHING
}
}
getOpens();
getClicks();
getTotal();
Im not sure if this is the correct way for accessing variables from other functions. I tried setting the globally but still no luck and the getTotal function is not able to get access to variables result and result2.
Why not use the return values from the function in your third function? It works without global variables.
function getOpens(){
return 10;
}
function getClicks(){
return 6;
}
function getTotal() {
if(getOpens() >= 10 && getClicks() < 1) {
//DO SOMETHING
}
}
few options
Option 1 - call functions in getTotal()
function getOpens(){
return 10;
}
function getClicks(){
return 6;
}
function getTotal(){
var result = getOpens();
var result2 = getClicks();
if(result >= 10 && result2 < 1)
{
//DO SOMETHING
}
}
Option 2 - pass params with function getTotal()
function getTotal(opens, myClicks){
if(opens >= 10 && myClicks< 1)
{
//DO SOMETHING
}
}
How about this :
var result;
var result2;
function getOpens(){
return 10;
}
function getClicks(){
return 6;
}
function getTotal(){
if(result >= 10 && result2 < 1)
{
console.log("DO SOMETHING");
} else {
console.log("DO SOMETHING ELSE");
}
}
result = getOpens();
result2 = getClicks();
getTotal();

Variadic curried sum function

I need a js sum function to work like this:
sum(1)(2) = 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10
etc.
I heard it can't be done. But heard that if adding + in front of sum can be done.
Like +sum(1)(2)(3)(4). Any ideas of how to do this?
Not sure if I understood what you want, but
function sum(n) {
var v = function(x) {
return sum(n + x);
};
v.valueOf = v.toString = function() {
return n;
};
return v;
}
console.log(+sum(1)(2)(3)(4));
JsFiddle
This is an example of using empty brackets in the last call as a close key (from my last interview):
sum(1)(4)(66)(35)(0)()
function sum(firstNumber) {
let accumulator = firstNumber;
return function adder(nextNumber) {
if (nextNumber === undefined) {
return accumulator;
}
accumulator += nextNumber;
return adder;
}
}
console.log(sum(1)(4)(66)(35)(0)());
I'm posting this revision as its own post since I apparently don't have enough reputation yet to just leave it as a comment. This is a revision of #Rafael 's excellent solution.
function sum (n) {
var v = x => sum (n + x);
v.valueOf = () => n;
return v;
}
console.log( +sum(1)(2)(3)(4) ); //10
I didn't see a reason to keep the v.toString bit, as it didn't seem necessary. If I erred in doing so, please let me know in the comments why v.toString is required (it passed my tests fine without it). Converted the rest of the anonymous functions to arrow functions for ease of reading.
New ES6 way and is concise.
You have to pass empty () at the end when you want to terminate the call and get the final value.
const sum= x => y => (y !== undefined) ? sum(x + y) : x;
call it like this -
sum(10)(30)(45)();
Here is a solution that uses ES6 and toString, similar to #Vemba
function add(a) {
let curry = (b) => {
a += b
return curry
}
curry.toString = () => a
return curry
}
console.log(add(1))
console.log(add(1)(2))
console.log(add(1)(2)(3))
console.log(add(1)(2)(3)(4))
Another slightly shorter approach:
const sum = a => b => b? sum(a + b) : a;
console.log(
sum(1)(2)(),
sum(3)(4)(5)()
);
Here's a solution with a generic variadic curry function in ES6 Javascript, with the caveat that a final () is needed to invoke the arguments:
const curry = (f) =>
(...args) => args.length? curry(f.bind(0, ...args)): f();
const sum = (...values) => values.reduce((total, current) => total + current, 0)
curry(sum)(2)(2)(1)() == 5 // true
Here's another one that doesn't need (), using valueOf as in #rafael's answer. I feel like using valueOf in this way (or perhaps at all) is very confusing to people reading your code, but each to their own.
The toString in that answer is unnecessary. Internally, when javascript performs a type coersion it always calls valueOf() before calling toString().
// invokes a function if it is used as a value
const autoInvoke = (f) => Object.assign(f, { valueOf: f } );
const curry = autoInvoke((f) =>
(...args) => args.length? autoInvoke(curry(f.bind(0, ...args))): f());
const sum = (...values) => values.reduce((total, current) => total + current, 0)
curry(sum)(2)(2)(1) + 0 == 5 // true
Try this
function sum (...args) {
return Object.assign(
sum.bind(null, ...args),
{ valueOf: () => args.reduce((a, c) => a + c, 0) }
)
}
console.log(+sum(1)(2)(3,2,1)(16))
Here you can see a medium post about carried functions with unlimited arguments
https://medium.com/#seenarowhani95/infinite-currying-in-javascript-38400827e581
Try this, this is more flexible to handle any type of input. You can pass any number of params and any number of paranthesis.
function add(...args) {
function b(...arg) {
if (arg.length > 0) {
return add(...[...arg, ...args]);
}
return [...args, ...arg].reduce((prev,next)=>prev + next);
}
b.toString = function() {
return [...args].reduce((prev,next)=>prev + next);
}
return b;
}
// Examples
console.log(add(1)(2)(3, 3)());
console.log(+add(1)(2)(3)); // 6
console.log(+add(1)(2, 3)(4)(5, 6, 7)); // 28
console.log(+add(2, 3, 4, 5)(1)()); // 15
Here's a more generic solution that would work for non-unary params as well:
const sum = function (...args) {
let total = args.reduce((acc, arg) => acc+arg, 0)
function add (...args2) {
if (args2.length) {
total = args2.reduce((acc, arg) => acc+arg, total)
return add
}
return total
}
return add
}
document.write( sum(1)(2)() , '<br/>') // with unary params
document.write( sum(1,2)() , '<br/>') // with binary params
document.write( sum(1)(2)(3)() , '<br/>') // with unary params
document.write( sum(1)(2,3)() , '<br/>') // with binary params
document.write( sum(1)(2)(3)(4)() , '<br/>') // with unary params
document.write( sum(1)(2,3,4)() , '<br/>') // with ternary params
ES6 way to solve the infinite currying. Here the function sum will return the sum of all the numbers passed in the params:
const sum = a => b => b ? sum(a + b) : a
sum(1)(2)(3)(4)(5)() // 15
function add(a) {
let curry = (b) => {
a += b
return curry;
}
curry[Symbol.toPrimitive] = (hint) => {
return a;
}
return curry
}
console.log(+add(1)(2)(3)(4)(5)); // 15
console.log(+add(6)(6)(6)); // 18
console.log(+add(7)(0)); // 7
console.log(+add(0)); // 0
Here is another functional way using an iterative process
const sum = (num, acc = 0) => {
if !(typeof num === 'number') return acc;
return x => sum(x, acc + num)
}
sum(1)(2)(3)()
and one-line
const sum = (num, acc = 0) => !(typeof num === 'number') ? acc : x => sum(x, acc + num)
sum(1)(2)(3)()
You can make use of the below function
function add(num){
add.sum || (add.sum = 0) // make sure add.sum exists if not assign it to 0
add.sum += num; // increment it
return add.toString = add.valueOf = function(){
var rtn = add.sum; // we save the value
return add.sum = 0, rtn // return it before we reset add.sum to 0
}, add; // return the function
}
Since functions are objects, we can add properties to it, which we are resetting when it's been accessed.
we can also use this easy way.
function sum(a) {
return function(b){
if(b) return sum(a+b);
return a;
}
}
console.log(sum(1)(2)(3)(4)(5)());
To make sum(1) callable as sum(1)(2), it must return a function.
The function can be either called or converted to a number with valueOf.
function sum(a) {
var sum = a;
function f(b) {
sum += b;
return f;
}
f.toString = function() { return sum }
return f
}
function sum(a){
let res = 0;
function getarrSum(arr){
return arr.reduce( (e, sum=0) => { sum += e ; return sum ;} )
}
function calculateSumPerArgument(arguments){
let res = 0;
if(arguments.length >0){
for ( let i = 0 ; i < arguments.length ; i++){
if(Array.isArray(arguments[i])){
res += getarrSum( arguments[i]);
}
else{
res += arguments[i];
}
}
}
return res;
}
res += calculateSumPerArgument(arguments);
return function f(b){
if(b == undefined){
return res;
}
else{
res += calculateSumPerArgument(arguments);
return f;
}
}
}
let add = (a) => {
let sum = a;
funct = function(b) {
sum += b;
return funct;
};
Object.defineProperty(funct, 'valueOf', {
value: function() {
return sum;
}
});
return funct;
};
console.log(+add(1)(2)(3))
After looking over some of the other solutions on here, I would like to provide my two solutions to this problem.
Currying two items using ES6:
const sum = x => y => (y !== undefined ) ? +x + +y : +x
sum(2)(2) // 4
Here we are specifying two parameters, if the second one doesnt exist we just return the first parameter.
For three or more items, it gets a bit trickier; here is my solution. For any additional parameters you can add them in as a third
const sum = x => (y=0) => (...z) => +x + +y + +z.reduce((prev,curr)=>prev+curr,0)
sum(2)()()//2
sum(2)(2)()//4
sum(2)(2)(2)//6
sum(2)(2)(2,2)//8
I hope this helped someone

Categories

Resources