On Thu, May 17, 2018 at 4:16 PM, Ben Fletcher <bfle...@gmail.com> wrote:
> Consider adding the array .map() implementation directly to the String
prototype.
>
> Here is a possible polyfill:
>
>     String.prototype.map = function (fn) {
>       return Array.prototype.map
>         .call(this, fn)
>         .join('');

Recommend something using the string's iterator instead, since the version
above will visit code units, not codepoints (characters). Crude unoptimized
version (https://jsfiddle.net/dkty51ys/):

```js
Object.defineProperty(String.prototype, "map", {
    value: function(fn, thisArg = undefined) {
        let result = "";
        for (const ch of this) {
            result += fn.call(thisArg, ch);
        }
        return result;
    }
});
```

or via conversion to array and back (https://jsfiddle.net/r0uqgx65/):

```js
Object.defineProperty(String.prototype, "map", {
    value: function(fn, thisArg = undefined) {
        return [...this].map(fn, thisArg).join("");
    }
});
```

> This replaces the common pattern of splitting, mapping, joining
> strings for processing.

Is it really that common? If so, the footgun available (iterating code
units rather than codepoints), could be an argument in favor...

-- T.J. Crowder
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to