Skip to content Skip to sidebar Skip to footer

Calculating With Functions Codewars Problem

I'm trying to grasp my head around how these functions are being called inside one another. Could someone walk me through how they are running? Does seven() get called first which

Solution 1:

I works by calling the function from inside to the outer funtion. As illustration, the function and their call with paramters and their following calls.

five()
    expression(5)
        5times(5) 
    functionwith closure over x = 5seven(function)
    expression(7, function)
        function(7)
35

At the end, you find the same result, but with an array of the functions in a reversed order. The functions get called with the accumulator, which returns the result of the function call.

This approach is an actual implementation of the maybe later (or never) you can use the actual experimentalpipeline operator |>, which has the following syntax:

expression|>function

Or with your functions: undefined |> five |> times |> seven

functionexpression(number, operation) {
    console.log('expression');
    if (!operation) return number;
    returnoperation(number);
}

functionfive(operation) {
    console.log('five');
    returnexpression(5, operation);
}

functionseven(operation) {
    console.log('seven');
    returnexpression(7, operation);
}

functiontimes(x) {
    console.log('times');
    returnfunction(y) {
        return y * x;
    }
}

console.log(seven(times(five()))); // 35console.log([five, times, seven].reduce((value, fn) =>fn(value), undefined))

Solution 2:

I did this in python and can help explain with some code:

defseven(operation = None):
    if operation == None:
        return5else:
        return operation(5)
deffive(operation = None):
     if operation == None:
        return5else:
        return operation(5)
deftimes(number):
    returnlambda y: y * number

The most important part of what you are doing is setting an abstract function "y" in the "times" function. the order that functions flow through given seven(times(five())) is from the inside to the outside five() = 5 times(5) = abstract function: y5 seven(y5) #the abstract class is given 7 as an argument to the abstract function y = 7 so, 5 * 7 = 35

Post a Comment for "Calculating With Functions Codewars Problem"