๐Ÿ‘”Array extension

JS โŸฉ value โŸฉ objectโŸฉ built-in โŸฉ Array โŸฉ extension

add custom methods to Array.prototype.

// 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 = {};

Last updated