Skip to content

Commit 96ce392

Browse files
committed
more topics covered
1 parent 26cde4c commit 96ce392

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

object-prototype/index.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,35 @@ console.log([1,2,3].describe()); // Output: This object has keys: 0, 1, 2
4444
// - Use Object.defineProperty to avoid polluting for...in loops.
4545
// - Always check if the property exists before defining.
4646
// - Avoid in production unless absolutely necessary.
47+
48+
49+
// =============================
50+
// Array.prototype Extension Example
51+
// =============================
52+
// WARNING: Modifying Array.prototype is discouraged in production for the same reasons as Object.prototype.
53+
// This is for educational/demo purposes only.
54+
55+
// Example: Add a custom function to Array.prototype
56+
if (!Array.prototype.firstAndLast) {
57+
Object.defineProperty(Array.prototype, 'firstAndLast', {
58+
value: function() {
59+
if (this.length === 0) return { first: undefined, last: undefined };
60+
return { first: this[0], last: this[this.length - 1] };
61+
},
62+
enumerable: false
63+
});
64+
}
65+
66+
// Usage:
67+
const arr = [10, 20, 30, 40];
68+
console.log(arr.firstAndLast()); // Output: { first: 10, last: 40 }
69+
70+
// Chaining with default methods:
71+
const mapped = arr.map(x => x * 2).firstAndLast();
72+
console.log(mapped); // Output: { first: 20, last: 80 }
73+
74+
// Works with empty arrays too:
75+
console.log([].firstAndLast()); // Output: { first: undefined, last: undefined }
76+
77+
// Clean up (optional):
78+
// delete Array.prototype.firstAndLast;

0 commit comments

Comments
 (0)