Array state will be cached in iOS 12 Safari. Is it a bug or feature? Array state will be cached in iOS 12 Safari. Is it a bug or feature? ios ios

Array state will be cached in iOS 12 Safari. Is it a bug or feature?


It's definitely a BUG! And it's a very serious bug.

The bug is due to the optimization of array initializers in which all values are primitive literals. For example, given the function:

function buildArray() {    return [1, null, 'x'];}

All returned array references from calls to buildArray() will link to the same memory, and some methods such as toString() will have their results cached. Normally, to preserve consistency, any mutable operation on such optimized arrays will copy the data to a separate memory space and link to it; this pattern is called copy-on-write, or CoW for short.

The reverse() method mutates the array, so it should trigger a copy-on-write. But it doesn't, because the original implementor (Keith Miller of Apple) missed the reverse() case, even though he had written many testcases.

This bug was reported to Apple on August 21. The fix landed in the WebKit repository on August 27 and shipped in Safari 12.0.1 and iOS 12.1 on October 30, 2018.


I wrote a lib to fix the bug.https://www.npmjs.com/package/array-reverse-polyfill

This is the code:

(function() {  function buggy() {    var a = [1, 2];    return String(a) === String(a.reverse());  }  if(!buggy()) return;  var r = Array.prototype.reverse;  Array.prototype.reverse = function reverse() {    if (Array.isArray(this)) this.length = this.length;    return r.call(this);  }})();