Topic 37 of 37
Machine Coding
Overview
A polyfill is a piece of code that provides the technology that you expect the browser to provide natively. Writing polyfills for standard methods (map, filter, reduce, bind, promise.all) is the most common JavaScript interview task for senior engineers. It proves you understand how the engine works internally.
Syntax
Notice how 'this' is used to access the array elements. The callback is executed with three arguments: current element, index, and the array itself.
Writing Array.prototype.myMap
javascript
Array.prototype.myMap = function(callback) {
const result = [];
// 'this' refers to the array calling the method
for (let i = 0; i < this.length; i++) {
// Array methods skip empty slots!
if (this.indexOf(this[i]) > -1) {
result.push(callback(this[i], i, this));
}
}
return result;
};
console.log([1, 2, 3].myMap(x => x * 2)); // [2, 4, 6]Common Pitfalls
- Using an arrow function on the prototype. `Array.prototype.myMap = () => {}` will break because 'this' will point to the Window, not the array.
Interview Tips
- Always handle edge cases in polyfills: what if the array is empty? What if the callback isn't a function? What if there are empty slots (e.g. `new Array(5)`)?
Real-World Example
Polyfilling Promise.all to understand asynchronous orchestration.
example
javascript
Promise.myAll = function(promises) {
return new Promise((resolve, reject) => {
const results = [];
let completed = 0;
if (promises.length === 0) resolve(results);
promises.forEach((promise, index) => {
Promise.resolve(promise).then(value => {
results[index] = value;
completed++;
if (completed === promises.length) resolve(results);
}).catch(reject); // Reject immediately on first error
});
});
};