Skip to content Skip to sidebar Skip to footer

Convert Arrow Function To Function Expression

I have a function with a map object: function xml_encode(s) { return Array.from(s).map(c => { var cp = c.codePointAt(0); return ((cp > 127) ? '&#' + cp + ';' : c);

Solution 1:

You're missing the argument of your function so try this

functionxml_encode(s) {
  returnArray.from(s).map(function(c) {
    var cp = c.codePointAt(0);
    return ((cp > 127) ? '&#' + cp + ';' : c);
  }).join('');
}

Solution 2:

You are missing the c paramter to your anonymous function.

function xml_encode(s)
{
  return Array.from(s).map(
    function(c) {
      //use charCodeAt for IE or use a polyfill
      //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt#Polyfill
      var cp = c.codePointAt(0); 
      return ((cp > 127) ? '&#' + cp + ';' : c);
    }
  ).join('');
}

Bonus: You might want to use s.split('') instead of Array.from(s) for better performance and browser support. String.prototype.split is supported in every browser while Array.from is not supported in IE for example. split is also 30% faster on Chrome and 80% faster on FF on my PC.

Solution 3:

Try to modify your code as below (you are missing an argument in the function):

functionxml_encode(s) {
  returnArray.from(s).map(function (c) {
    var cp = c.codePointAt(0);
    return cp > 127 ? '&#' + cp + ';' : c;
  }).join('');
}

Since, you are using Array.from and codePointAt function, they don't support IE Browser. To use them in the IE browser, we need to add the related popyfill before using this function.

Polyfill code as below (I have created a sample to test it, it works well on my side.):

// Production steps of ECMA-262, Edition 6, 22.1.2.1if (!Array.from) {
        Array.from = (function () {
            var toStr = Object.prototype.toString;
            var isCallable = function (fn) {
                returntypeof fn === 'function' || toStr.call(fn) === '[object Function]';
            };
            var toInteger = function (value) {
                varnumber = Number(value);
                if (isNaN(number)) { return0; }
                if (number === 0 || !isFinite(number)) { returnnumber; }
                return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
            };
            var maxSafeInteger = Math.pow(2, 53) - 1;
            var toLength = function (value) {
                var len = toInteger(value);
                returnMath.min(Math.max(len, 0), maxSafeInteger);
            };

            // The length property of the from method is 1.returnfunctionfrom(arrayLike/*, mapFn, thisArg */) {
                // 1. Let C be the this value.var C = this;

                // 2. Let items be ToObject(arrayLike).var items = Object(arrayLike);

                // 3. ReturnIfAbrupt(items).if (arrayLike == null) {
                    thrownewTypeError('Array.from requires an array-like object - not null or undefined');
                }

                // 4. If mapfn is undefined, then let mapping be false.var mapFn = arguments.length > 1 ? arguments[1] : voidundefined;
                var T;
                if (typeof mapFn !== 'undefined') {
                    // 5. else// 5. a If IsCallable(mapfn) is false, throw a TypeError exception.if (!isCallable(mapFn)) {
                        thrownewTypeError('Array.from: when provided, the second argument must be a function');
                    }

                    // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.if (arguments.length > 2) {
                        T = arguments[2];
                    }
                }

                // 10. Let lenValue be Get(items, "length").// 11. Let len be ToLength(lenValue).var len = toLength(items.length);

                // 13. If IsConstructor(C) is true, then// 13. a. Let A be the result of calling the [[Construct]] internal method // of C with an argument list containing the single item len.// 14. a. Else, Let A be ArrayCreate(len).var A = isCallable(C) ? Object(newC(len)) : newArray(len);

                // 16. Let k be 0.var k = 0;
                // 17. Repeat, while k < len… (also steps a - h)var kValue;
                while (k < len) {
                    kValue = items[k];
                    if (mapFn) {
                        A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
                    } else {
                        A[k] = kValue;
                    }
                    k += 1;
                }
                // 18. Let putStatus be Put(A, "length", len, true).
                A.length = len;
                // 20. Return A.return A;
            };
        }());
    }

    /*! https://mths.be/codepointat v0.2.0 by @mathias */if (!String.prototype.codePointAt) {
        (function () {
            'use strict'; // needed to support `apply`/`call` with `undefined`/`null`var defineProperty = (function () {
                // IE 8 only supports `Object.defineProperty` on DOM elementstry {
                    varobject = {};
                    var $defineProperty = Object.defineProperty;
                    var result = $defineProperty(object, object, object) && $defineProperty;
                } catch (error) { }
                return result;
            }());
            var codePointAt = function (position) {
                if (this == null) {
                    throwTypeError();
                }
                varstring = String(this);
                var size = string.length;
                // `ToInteger`var index = position ? Number(position) : 0;
                if (index != index) { // better `isNaN`
                    index = 0;
                }
                // Account for out-of-bounds indices:if (index < 0 || index >= size) {
                    returnundefined;
                }
                // Get the first code unitvar first = string.charCodeAt(index);
                var second;
                if ( // check if it’s the start of a surrogate pair
                    first >= 0xD800 && first <= 0xDBFF && // high surrogate
                    size > index + 1// there is a next code unit
                ) {
                    second = string.charCodeAt(index + 1);
                    if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulaereturn (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
                    }
                }
                return first;
            };
            if (defineProperty) {
                defineProperty(String.prototype, 'codePointAt', {
                    'value': codePointAt,
                    'configurable': true,
                    'writable': true
                });
            } else {
                String.prototype.codePointAt = codePointAt;
            }
        }());
    }

More detail information, please check the Array.from() method and the codePointAt() method

Post a Comment for "Convert Arrow Function To Function Expression"