Convert Arrow function to function expression

convert arrow function to normal function online
arrow function javascript
arrow function vs function
arrow function return
javascript arrow function return object
arrow functions typescript
arrow function in react w3schools
jquery arrow function

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);
 }).join('');
}

This has worked great except it has broken everything when running Internet Explorer 11.

I tried to rewrite the code using a function expression however I get a c is not defined:

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

Unfortunately this needs to be a public-facing function and I am required to support IE11 for now. How do I rewrite this function to work with IE11?

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

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

Convert to Arrow Function Expressions, Turn regular function declarations into arrow function expressions. Teacher's Notes; Video Transcript; Downloads. converting this function declaration to an arrow function expression, 1:26. is almost exactly the same as our first example, except for one difference. 1:30. Do you know what it is? 1:33. Yep, you got it. 1:35. This function receives two parameters, so they have to be enclosed with parentheses. 1:40. Here's my solution for our final function

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.

JavaScript, An arrow function looks similar to a function expression — it's just are three challenges — See if you can convert them into arrow functions! An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors.

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

function xml_encode(s) {
  return Array.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.1
    if (!Array.from) {
        Array.from = (function () {
            var toStr = Object.prototype.toString;
            var isCallable = function (fn) {
                return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
            };
            var toInteger = function (value) {
                var number = Number(value);
                if (isNaN(number)) { return 0; }
                if (number === 0 || !isFinite(number)) { return number; }
                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);
                return Math.min(Math.max(len, 0), maxSafeInteger);
            };

            // The length property of the from method is 1.
            return function from(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) {
                    throw new TypeError('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] : void undefined;
                var T;
                if (typeof mapFn !== 'undefined') {
                    // 5. else
                    // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
                    if (!isCallable(mapFn)) {
                        throw new TypeError('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(new C(len)) : new Array(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 elements
                try {
                    var object = {};
                    var $defineProperty = Object.defineProperty;
                    var result = $defineProperty(object, object, object) && $defineProperty;
                } catch (error) { }
                return result;
            }());
            var codePointAt = function (position) {
                if (this == null) {
                    throw TypeError();
                }
                var string = 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) {
                    return undefined;
                }
                // Get the first code unit
                var 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-formulae
                        return (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

JavaScript Arrow Function, lexical scoping — 'this' refers to it's current surrounding scope and no further. An arrow function looks similar to a function expression — it’s just shorter. Again we assign an anonymous function to a named variable. The syntax of the arrow function consists of zero or more parameters, an arrow => and then concludes with the function statements. const name = (parameters) => {

Learn ES6 The Dope Way Part II: Arrow functions and the 'this , What is the difference between Arrow function and normal function? For example - the popular airbnb eslint configuration enforces the use of JavaScript arrow functions any time you are creating an anonymous function. However, like anything in engineering, arrow functions come with positives and negatives. There are tradeoffs to their use. Learning those tradeoffs is key to using arrow functions well.

Difference between regular functions and arrow functions , You're missing the argument of your function so try this function xml_encode(s) { return Array.from(s).map(function(c) { var cp = c. 0:00 This is the final video in the practicing Arrow functions syntax workshop. 0:01 You've made some awesome progress so far. 0:06 Hopefully by now, 0:08 you're feeling really confident in how to correctly write Arrow functions.

Convert Arrow function to function expression, Okay, since I have the base setup complete for getting arrow function conversions working, I am opening this up if someone would like to help get the conversion  Given how arrow functions work, the latter way of parenthesizing should be preferred from now on. 13.6.3 Parenthesizing arrow function with expression bodies #. If you want to understand why you can’t invoke an arrow function by putting parentheses immediately after it, you have to examine how expression bodies work: parentheses after an expression body should be part of the expression, not

Comments
  • You left out the parameter: function(c) ... — you'll also need the Array.from() polyfill from MDN
  • or keep ES6 and use a transpiler
  • I don't even have to test this, it won't work in IE11.
  • I don't even have to test this, it won't work in IE11.
  • True, but thats not what you question was about, I will however see if I can make it work for IE
  • Using split and a codePointAt polyfill or charCodeAt works in IE 11.