What is this pattern called f (a) (b) (c)?

function setStyle(x) {
    with (x.style) {
        padding = '10px'
        marginBottom = '10px'
        width = '100%'
    }
    return setStyle
}

setStyle(account)(password)(login)

      

I use the above pattern a lot, but when I need to talk about it, I have no idea what is it called? How to refer to this approach in conversation?

UPDATE:

Someone closed this question as a duplicate, but I don't understand why it is a duplicate. Another question is about some frameworks, the poster is trying to understand the code. I am not trying to understand the code, I am asking about an English term for a famous pattern. While the concept under discussion is the same, the question is different. It's like "Who was the youngest in the Jasckson Five" and "Whose album is Thriller" are both the same question, only because it happens to about the same person. But these are different questions, and Not the same.

+3


source to share


1 answer


This pattern is not "function chaining" because chaining (= composed, pipelined) functions work by passing the result of one function as an argument to the next. For example, if you have something like:

str = removeBadChars(str)
str = makeLowerCase(str)
str = convertToURL(str)

      

you can rewrite this more succinctly like

str = chain(removeBadChars, makeLowerCase, convertToURL)(str)

      

(Exercise: write chain()

).

Your template doesn't have a name, probably because it's pretty useless. Mr. Crockford came up with <term> recursion , but it doesn't seem to be widely used.



Note that this pattern is essentially anti-functional, because in functional programming we prefer to work with pure functions, whereas a "recursive" function can only do something useful as a side effect.

UPD: This reasoning refers to functions that just blindly return like in your example, however the syntax f()()()

can also be used with functions that return something else on every call. In this case, the "root" function takes a hidden parameter ("accumulator") used to wrap the state around. A good example of this approach would be chain()

, as stated above, but written in an applicative style chain(func1)(func2)(func3)

:

function chain(f, fun) {

    fun = fun || function(x) { return x };

    if(typeof f != "function")
        return fun(f);

    return function(x) {
        return chain(x, function(y) { return f(fun(y)) })
    }
}

// Example:

makeLowerCase  = function(str) { return str.toLowerCase() };
removeBadChars = function(str) { return str.replace(/\W/g, "") };
makeURL        = function(str) { return "http://" + str };

funcs = chain(makeLowerCase)(removeBadChars)(makeURL);
x = funcs('!!! HELLO ???');
alert(x);
      

Run codeHide result


In this case, this syntax is used to implement a "partial application" because we return a closure that calls the root function again with a predefined second argument.

+4


source







All Articles