Make WordPress Core

Ticket #30781: array-prototype-indexof-polyfill.php

File array-prototype-indexof-polyfill.php, 2.5 KB (added by westonruter, 12 years ago)

Polyfill plugin for Array.prototype.indexOf()

Line 
1<?php
2/**
3 * Plugin Name: Array.prototype.indexOf() polyfill for LTE IE8
4 * Description: As reported in WordPress Trac #30781, an error is happening in WP4.1.0 for IE8 users due to that browser's incomplete implementation of modern JS methods.
5 * Plugin URI: https://core.trac.wordpress.org/ticket/30781
6 * Author: Weston Ruter, XWP
7 * Author URI: https://xwp.co/
8 */
9
10/**
11 * Via https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
12 */
13function array_prototype_indexof_polyfill() {
14 ?>
15 <script>
16 // Production steps of ECMA-262, Edition 5, 15.4.4.14
17 // Reference: http://es5.github.io/#x15.4.4.14
18 if (!Array.prototype.indexOf) {
19 Array.prototype.indexOf = function(searchElement, fromIndex) {
20
21 var k;
22
23 // 1. Let O be the result of calling ToObject passing
24 // the this value as the argument.
25 if (this == null) {
26 throw new TypeError('"this" is null or not defined');
27 }
28
29 var O = Object(this);
30
31 // 2. Let lenValue be the result of calling the Get
32 // internal method of O with the argument "length".
33 // 3. Let len be ToUint32(lenValue).
34 var len = O.length >>> 0;
35
36 // 4. If len is 0, return -1.
37 if (len === 0) {
38 return -1;
39 }
40
41 // 5. If argument fromIndex was passed let n be
42 // ToInteger(fromIndex); else let n be 0.
43 var n = +fromIndex || 0;
44
45 if (Math.abs(n) === Infinity) {
46 n = 0;
47 }
48
49 // 6. If n >= len, return -1.
50 if (n >= len) {
51 return -1;
52 }
53
54 // 7. If n >= 0, then Let k be n.
55 // 8. Else, n<0, Let k be len - abs(n).
56 // If k is less than 0, then let k be 0.
57 k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
58
59 // 9. Repeat, while k < len
60 while (k < len) {
61 // a. Let Pk be ToString(k).
62 // This is implicit for LHS operands of the in operator
63 // b. Let kPresent be the result of calling the
64 // HasProperty internal method of O with argument Pk.
65 // This step can be combined with c
66 // c. If kPresent is true, then
67 // i. Let elementK be the result of calling the Get
68 // internal method of O with the argument ToString(k).
69 // ii. Let same be the result of applying the
70 // Strict Equality Comparison Algorithm to
71 // searchElement and elementK.
72 // iii. If same is true, return k.
73 if (k in O && O[k] === searchElement) {
74 return k;
75 }
76 k++;
77 }
78 return -1;
79 };
80 }
81 </script>
82 <?php
83}
84
85add_action( 'customize_controls_print_scripts', 'array_prototype_indexof_polyfill', 1 );