remove redundant code in method

Im using the following code which works but after reading about JS(im fairly new) I've noticed of 3 things.

  1. using return at the beginning of the method

  2. using ternary condition (not sure how to use it in this case)

  3. using reduce (not sure about this but maybe instead of the forEach)

is it possible to use it in the following code?

 get: function(document, oData) {
        var self = this;
        var oInnerHTML;
        if (oData) {
            var oParsedHTML = this._parseHtml(document);
            oInnerHTML = oParsedHTML;
            oData.forEach(function(configEntry) {
                oInnerHTML = self._routeExtentionTypes(configEntry, oInnerHTML);
            });
            oInnerHTML = this._convertBackToHtml(oInnerHTML);
        } else {
            oInnerHTML = document;
        }
         return oInnerHTML
    }

What the code is doing is

  1. getting HtmlString and parse it
  2. extend it according to the cofigEntry and the original HTML
  3. when the config entry was done it convert back to HTML

Answers 1

  • I think, you can try that with Array#reduce().

    Basically the reduce is doing what you want. It takes a start value and iterates an array and returns some value, as desired.

    The former code

    var oParsedHTML = this._parseHtml(document);
        oInnerHTML = oParsedHTML;
    oData.forEach(function(configEntry) {
        oInnerHTML = self._routeExtentionTypes(configEntry, oInnerHTML);
    });
    

    convertes to

    this._convertBackToHtml(oData.reduce(function (r, configEntry) {
        return self._routeExtentionTypes(configEntry, r);
    }, this._parseHtml(document))) :
    

    because the start value is now this._parseHtml(document) without the need of an additional variable and the return value becomes the new input value for the next iteration.

    get: function (document, oData) {
        var self = this;
        return oData ?
            this._convertBackToHtml(oData.reduce(function (r, configEntry) {
                return self._routeExtentionTypes(configEntry, r);
            }, this._parseHtml(document))) :
            document;
    }
    

Related Articles