Skip to content

Commit 4b14496

Browse files
Closure Teamcopybara-github
authored andcommitted
Fix polyfill for flat and flatMap to handle sparse arrays.
PiperOrigin-RevId: 508190440
1 parent 89e3802 commit 4b14496

File tree

6 files changed

+4460
-4390
lines changed

6 files changed

+4460
-4390
lines changed

src/com/google/javascript/jscomp/js/es6/array/flat.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,17 @@ $jscomp.polyfill('Array.prototype.flat', function(orig) {
3535
// TODO(sdh): Consider respecting Symbol.species (b/121061255).
3636
depth = depth === undefined ? 1 : depth;
3737
var flattened = [];
38-
for (var i = 0; i < this.length; i++) {
39-
var element = this[i];
38+
var flattenElementIntoArray = function(element) {
4039
if (Array.isArray(element) && depth > 0) {
4140
var inner = Array.prototype.flat.call(element, depth - 1);
4241
flattened.push.apply(flattened, inner);
4342
} else {
4443
flattened.push(element);
4544
}
46-
}
45+
};
46+
// Use Array.prototype explicitly since IE11 doesn't support forEach
47+
// on array-like NodeList
48+
Array.prototype.forEach.call(this, flattenElementIntoArray);
4749
return flattened;
4850
};
4951

src/com/google/javascript/jscomp/js/es6/array/flatmap.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ $jscomp.polyfill('Array.prototype.flatMap', function(orig) {
3434
*/
3535
var flatMap = function(callback, thisArg) {
3636
var mapped = [];
37-
for (var i = 0; i < this.length; i++) {
38-
var result = callback.call(thisArg, this[i], i, this);
37+
var mapAndFlattenElementIntoArray = function(element, index) {
38+
var result = callback.call(thisArg, element, index, this);
3939
if (Array.isArray(result)) {
4040
mapped.push.apply(mapped, result);
4141
} else {
@@ -47,7 +47,10 @@ $jscomp.polyfill('Array.prototype.flatMap', function(orig) {
4747
// non-Array.
4848
mapped.push(result);
4949
}
50-
}
50+
};
51+
// Use Array.prototype explicitly since IE11 doesn't support forEach
52+
// on array-like NodeList
53+
Array.prototype.forEach.call(this, mapAndFlattenElementIntoArray);
5154
return mapped;
5255
};
5356

0 commit comments

Comments
 (0)