Functions console.log not good - javascript

I came across this exercice on the code academy and I don't understand why my code does not work. can someone explain to me and help me? thank you so much!
Here we have a function, addTwo(), that adds 2 to whatever is passed into it. Below that, we’ve created what will be a higher-order function, checkConsistentOutput(). The purpose of the higher-order function will be to check the work of addTwo(). Let’s get started!
To begin, inside the body of checkConsistentOutput(), declare two variables: checkA and checkB:
checkA stores the sum val plus 2.
checkB stores the invocation of the func callback, with val as the argument.
Next, below the variables, write a conditional statement that checks if the value of checkA is equal to the value checkB. If true, return the result of the callback function. If false, return the string 'inconsistent results'.
Finally, using console.log(), log the invocation of checkConsistentOutput() with two arguments: the addTwo() function and any number.
THIS IS MY CODE:
const addTwo = num => {
return num + 2;
}
const checkConsistentOutput = (func, val) => {
let checkA = val + 2;
let checkB = func(val)
if (checkA === checkB) {
return func(val);
} else {
return 'inconsistent results';
}
}
console.log(addTwo(5));
I can't pass the number 3 dunno why?

You have to include checkConsistentOutput() in the log, eg:
console.log(checkConsistentOutput(addTwo, 5));

Related

I need help understanding 'Once' function by David Walsh

I'm trying to understand exactly how this Once function by David Walsh works:
`
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
// Usage
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada
`
I understand it takes a function as a argument, and returns a function that calls the passed function only once.
But I'm trying to understand what each part is doing. Can anyone help explain? especially this part:
result = fn.apply(context || this, arguments);
Why the OR sign? what is "this" and how is it getting the arguments from fn? What purpose does 'context' serve?
I wrote a similar once() function for school that returns the result of the passed function, and stores the result to return it again if the function attempts to get called again. It took a lot of trial and error, and I'm just trying to get a firm grasp on all the component parts of how this works.
`
function add(x, y) {
return x + y;
}
function once(fn) {
let timesRan = 0;
let result;
function doOnce() {
if (timesRan === 0) {
timesRan = 1;
result = fn.apply(this, arguments); //I don't understand how this gets the arguments from AddOnce
console.log(`did it once: ${result}`)
return result;
} else {
return result;
}
}
return doOnce;
}
var addOnce = once(add);
console.log(addOnce(1, 2)); // test first call, expected value: 3
console.log(addOnce(2, 5)); // test second call, expected value: 3
console.log(addOnce(8, 22)); // test third call, expected value: 3
`
The concept behind this in JavaScript is confusing, because when I write a function such as:
function getPersonName() {
return this.name
}
I expect that this be defined as a some object with a name attribute. Depending on the scope, I may have this be defined and no problems! But in order for a function such as the above to properly reference this, we need to tell it what it should reference when we use that keyword.
For example, it allows us to do the following:
var canOnlyFireOnce = once(function() {
console.log(this.name)
}, {name: "John"});
canOnlyFireOnce() // prints John
canOnlyFireOnce() // nada
It may be helpful to understand the bind function's use cases in JavaScript to understand why having this (no pun intended) is useful.
The meaning of the this context in function.apply is already explained in rb612's answer.
For the question about arguments, you need to know that
the arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. 

Understanding pipe function in JavaScript (functional programming)

I'm working through question 11 on bfe.dev's JavaScript coding exercises. The question asks to chain multiple basic math functions together via composition.
Here's some sample code that passes the provided test cases.
function pipe(funcs) {
let result;
return function (arg) {
result = arg;
for (let fn of funcs) {
result = fn(result);
}
return result;
}
}
And some driver code with the intended result, according to bfe.dev
pipe([
times(2),
plus(3),
times(4)
])
// (x * 2 + 3) * 4
I'm struggling to understand the implementation on a code-level. pipe receives an array of functions, and I understand the approach is to walk through the array and compute the result of each function, store that in the result variable, similar to an array reduce.
But I cannot wrap my head around how the return function works, and what arg would actually be. I would appreciate a line-by-line walkthrough if possible.
Thanks in advance!
The example probably needs a bit more to make sense:
const doMath = pipe([
times(2),
plus(3),
times(4)
])
const finalResult = doMath(5)
console.log(finalResult);
pipe's job is to create a new function. That new function has the text:
function (arg) {
result = arg;
for (let fn of funcs) {
result = fn(result);
}
return result;
}
And that is what gets assigned to doMath in my example. Then when i call doMath(5), it's going to execute the code, with arg equal to 5. It assigns 5 to result, and then starts looping through the functions (which it still has access to because this is a closure). Each function calculates a new value, which gets assigned to result, and then eventually the final result is returned. So in this case the calculation goes 5 => 10 => 13 => 52. 52 gets returned and then logged out.

Arguments Optional FreeCodeCamp Challenge

in need of help with a codecamp challenge:
Arguments Optional - The challenge
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional
My Question
I know this can be done with the arguments object (see figure 1), where I can call the function again when the second value is undefined so I've gone for a different approach; However, my code of using currying works but becomes an issue with 'addTogether(5)(7);'
Issue ->
I get the returned value of 12 but doesn't get approved in the code challenge.
I did originally return the value inside the sum function but the challenge required the sum value to be returned in addTogether function, which I did so now it resulting in the following
addTogether(2,3); // now working
addTogether(5)(7); // NOT working
addTogether(23, 30); // now working
Is there something I'm doing wrong that's resulting in the test case failing even though the correct value is returned?
let val = 0;
function sum(a, b) {
val = a + b;
}
function sumTwoAnd(sumFunc) {
return function addTogether(...params) {
let numsArr = [...params];
const res = numsArr.every(el => typeof el === 'number');
if (res === false) return;
if (numsArr.length >= sumFunc.length) {
sumFunc(...numsArr);
} else {
return function(...args2) {
let newArr = numsArr.concat(args2);
addTogether(...newArr);
}
}
console.log(val);
return val;
}
}
let addTogether = sumTwoAnd(sum);
addTogether(2,3);
addTogether(5)(7);
addTogether(23, 30);
Figure 1
Shows how I can get 'test(5)(7)' the second parameter from the function
function test() {
const [f, s] = arguments;
console.log(f, s)
if (s === undefined) {
return s => test(f, s)
}
}
test(23, 30);
test(5)(7);
You declared addTogether using let, so the declaration won't be hoisted above the point where it was defined. This is making your recursive call in the else statement fail, since addTogether() doesn't exist that far up.
You might want to extract the function you're returning in sumTwoAnd() as a separate function definition, so it can freely call itself, similar to your Figure 1 example.
Or you can call sumTwoAnd() instead to regain the function, then pass newArr to said function.
Instead of calling the function I have now returned it...
return addTogether(...newArr);
This now works :)

Not understanding higher order functions (problem example using javascript)

I'm studying Javascript basics, particularly higher order functions, at the moment. I have read many articles and watched as many videos where people explain the basic definition and demonstrate the most basic construction of a higher order function. However, when I encounter an actual problem, I am lost. Here is an example (this is just for my personal study, not for a grade or for work):
Write a maybe function that, given a predicate (a function that returns a boolean value) and any other function, only calls the latter if the former returns true: maybe(x => x > 100, myFn). If the predicate returns true, the value of x should be passed to myFn. If the predicate returns false, x should be returned unchanged.
I don't understand how to pass the value of x from one function to another...
I solved this by adding a number argument to maybe, in addition to the predicate function and callback function. However, only two parameters are specified in the prompt, so I guess I'm not doing it correctly. Here is what I did:
//predicate (evaluates to a boolean)
const notZero = function(x) {
//console.log('predicate runs!');
return x !== 0;
}
//callback (does something within the main function)
const plusOne = function(x) {
//console.log('callback runs!');
return x + 1;
}
//checking if my predicate works
//test(notZero(1), true); // => test passed!
//another callback
const myFn = function(x) {
return x - 100;
}
//main function
function maybe(number, predicate, callback) {
if (predicate(number) === true) {
//console.log('predicate === true');
//console.log(callback(number));
return callback(number);
} else {
return number;
}
}
test(maybe(1, notZero, plusOne), 2);
test(maybe(0, notZero, plusOne), 0);
test(maybe(101, x => x > 100, myFn), 1);
test(maybe(99, x => x > 100, myFn), 99);
EDIT: As shared below, maybe can now take only 2 parameters (the predicate and the callback) because it now returns a function whose parameter is number. That's the idea I was looking for.
function maybe(predicate, callback) {
return function (number) {
if (predicate(number) === true) {
return callback(number);
} else {
return number;
}
}
}
It's technically impossible. x is locked out of the world in predicate's scope. There's no way you may extract it out of this function.
Apart from that, as you correctly assume in your code, we logically need to communicate x to both predicate & callback. Otherwise, what's the point of maybe at all?
Since then, your solution is one of very few possible ones.
You may "decorate" it nicer with currying. The idea is precisely identical as in your code but if you'll do so, you will be able to call the final function exactly with 2 arguments.
const setMaybeBase => x => (predicate, callback) => predicate(x) ? callback(x) : x;
// use it later this way
const maybe42 = setMaybeBase(42);
maybe42(yourFn, yourFnTwo);
This is a huge overkill unless the argument you pass to setMaybeBase is for example a complex object you are going to work with.
Alternatively, you might go wild & use a function to get the x as well.
Nevertheless, always remember that the easiest solution is the best one.
Here is a real-world example of maybe function taken straight from node.js repo:
function maybeCallback(cb) {
if (typeof cb === 'function')
return cb;
throw new ERR_INVALID_CALLBACK(cb);
}

Closure returns what is supposed to and also undefined

I'm practicing closures and my assigment for now is to :
Write a function once that accepts a callback as input and returns a function.
When the returned function is called the first time, it should call the callback
and return that output. If it is called any additional times, instead of calling
the callback again it will simply return the output value from the first time it
was called.
My callback is:
const addByX = function (num1) {
let number = num1;
function adding(num2) {
console.log(number + num2);
}
return adding;
}
//addByX(2)(8);
let addByTwo = addByX(2);
And my main function is:
const once = function (func) {
let isFirst = true;
let firstOutput;
function inside(numberToPass) {
if (isFirst) {
firstOutput = func(numberToPass);
isFirst = false;
return func(numberToPass);
} else {
return firstOutput;
}
}
return inside;
}
It works, but when I invoke it
const onceFunc = once(addByTwo);
console.log(onceFunc(4)); //should log 6
console.log(onceFunc(10)); //should log 6
it returns my values and also undefined.
And I really can't understand why would it.
Maybe if it works I should not ask this kind of questions, but I'm really curious.
Debugger couldn't clearly answer my question.
I'm suspicious it has something to do with console.log, as abvious as it looks.
Here in JS Bin
The function addByX returns another function, adding. But adding doesn't return anything; it just logs. It's return value is undefined.
I think you intended it to look like this:
const addByX = function (num1) {
let number = num1;
function adding(num2) {
return number + num2;
}
return adding;
}
So the reason that it "worked" is because the callback was printing to the console, rather than where you are invoking it.

Categories

Resources