๐Array extension
JS โฉ value โฉ objectโฉ built-in โฉ Array โฉ extension
add custom methods to Array.prototype.
replit โฉ Array extension
// 2023.01.16 - 22:55 - (+) .maxIn()
// 2022.12.29 - 20:14 - (+) .removeDuplicates(), .union(), .isEmpty
// --------------------------------------------------------------------
const { floor, random } = Math;
// โญ Array extension
// --------------------------------------------------------------------
// ๐ธ .isEmpty
// ๐ธ .randomElement - random element
// ๐น .removeDuplicates() - remove duplicate element (new copy)
// ๐น .union() - union with unique elements
// ๐น .maxIn() - max quantity in array
// --------------------------------------------------------------------
Object.defineProperties(Array.prototype, {
// ๐ธ .isEmpty
isEmpty: {
get() {
return this.length === 0;
},
},
// ๐ธ .randomElement
randomElement: {
get() {
return this[floor(random() * this.length)];
},
},
// ๐น .removeDuplicates()
removeDuplicates: {
value: function() {
return [... new Set(this)]; // new array (non-mutating)
},
},
// ๐น .union()
union: {
value: function(...arrays) {
return this.concat(...arrays).removeDuplicates();
},
},
// ๐น .maxIn()
// - max quantity in array
maxIn: {
value: function(quantity) {
return this
.map(x => quantity(x))
.reduce((max, value) => max = value > max ? value : max);
},
},
});
// export
module.exports = {};
[].isEmpty, // true
[1,2,3].randomElement, // (random)
[ 1, 1, 2, 3, 2, 3, 4 ].removeDuplicates(), // [ 1, 2, 3, 4 ]
[1].concat([1,2,3],[2,3,4]), // [ 1, 1, 2, 3, 2, 3, 4 ]
[1].union([1,2,3],[2,3,4]), // [ 1, 2, 3, 4 ]
const touchEvents = ['touchstart', 'touchmove', 'touchend'];
const mouseEvents = ['mousedown', 'mouseup', 'click'];
const eventTypes = [...touchEvents, ...mouseEvents];
eventTypes.maxIn(x => x.length) // 10
๐ๅ ถไป็ฏไพ๏ผ
touch event - use array.maxIn(quantity).
arr.randomElement - random element.
arr.removeDuplicates() - remove duplicate elements (new copy).
Last updated