0

I need to use a function like this for multiple times with different ids based on different conditions (e.g. select values). I don't want to write a different function for every id because there will be lots of them in the future.

var getValue = function(id){

    var Element = document.getElementById(id);

    if(Element){
        if(Element.value){
            return " " + Element.value;
        }
        return "";
    }
    return "";
}

I have an array including some other functions:

FunctionList = [ SomeFunction, SomeFunction2 ];

Based on some conditions, I add getValue function with different parameters to this array.

FunctionList.push(getValue(SomeId1));
FunctionList.push(getValue(SomeId2));
FunctionList.push(getValue(SomeOtherId));

In the end, I need to add outputs of my functions (which are strings) to another string.

var updateCode = function(){
    var code = CodeHeader;
    for (var i=0; i<FunctionList.length; i++){
        code += FunctionList[i]();
    } 
    return code;
}

But I am unable to use it like this since some items of array are not function names now. I like pure js solutions, but if it's not possible I can go for jQuery or so.

1

1 Answer 1

1

You can use bind to create such a tailored function on the fly:

FunctionList.push(getValue.bind(null, SomeId1));

The first argument (null here) will act as this during function execution.

This differs from what you had:

FunctionList.push(getValue(SomeId1));

...as here you don't push a function, but the result of a function execution. bind however, will not execute the function, but create a new one from the given function.

Alternative

In your example you call the same function with different arguments. If that is always the case, you could also go for an array of only arguments:

argumentList.push(SomeId1); // Not the function, just the argument
// ...etc

And then updateCode would become:

var updateCode = function(){
    var code = CodeHeader;
    for (var i=0; i<argumentList.length; i++){
        code += getValue(argumentList[i]);
    } 
    return code;
}

... or shorter by using map:

var updateCode = () => CodeHeader + argumentList.map(getValue).join("");

As in your getValue function, you prefix the returned value with a space, you could omit that prefix, and just use .join(" ") in the above one-liner. The downside is that it would not deal the same way with empty return values.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.