Haris Khan
Haris Khan

Reputation: 171

JS: Making a better function that returns conditional statement

function conditionForLinks(textNum, linkNum){
            if (textNum == undefined || linkNum == undefined){
                    return "${typeof(contentAsset.custom.brandInfoLinkUrl) !== 'undefined' && contentAsset.custom.brandInfoLinkUrl && typeof(contentAsset.custom.brandInfoLinkText) !== 'undefined' && contentAsset.custom.brandInfoLinkText}"
                }else{
                    return "${typeof(contentAsset.custom.brandInfoLinkUrl"+textNum+") !== 'undefined' && contentAsset.custom.brandInfoLinkUrl"+textNum+" && typeof(contentAsset.custom.brandInfoLinkText"+linkNum+") !== 'undefined' && contentAsset.custom.brandInfoLinkText"+textNum+"}"
                }
        };

So I want this function to return the conditional statement. When no arguments are provided it should display the whole statement without any numbers(function arguments).Else put the arguments(numbers) in the statement. My solution does not looks elegant.

Upvotes: 2

Views: 36

Answers (2)

kakogo
kakogo

Reputation: 41

function conditionForLinks (textNum, linkNum) {
    if(textNum == undefined || linkNum == undefined) {
        textNum = '';
        linkNum = '';
    }
    return ["${typeof(contentAsset.custom.brandInfoLinkUrl", textNum, ") !== 'undefined' && contentAsset.custom.brandInfoLinkUrl", textNum, " && typeof(contentAsset.custom.brandInfoLinkText", linkNum, ") !== 'undefined' && contentAsset.custom.brandInfoLinkText", textNum, "}"].join('');
}

Upvotes: 2

Simon Farrugia
Simon Farrugia

Reputation: 100

I don't know exactly what you are trying to accomplish but here is something:

function conditionForLinks(textNum, linkNum){

  textNum = (textNum == null) ? "" : textNum;
  linkNum = (linkNum == null) ? "" : linkNum;

  return "${typeof(contentAsset.custom.brandInfoLinkUrl"+textNum+") !== 'undefined' && contentAsset.custom.brandInfoLinkUrl"+textNum+" && typeof(contentAsset.custom.brandInfoLinkText"+linkNum+") !== 'undefined' && contentAsset.custom.brandInfoLinkText"+textNum+"}";
}

Upvotes: 1

Related Questions