JSFiddle - React, Tailwind, and code Playground

by thetenfold

JavaScript

function cArray() {
    var interceptors = [], // holds our listener functions
        values = [], // holds our actual array values
        args = [].slice.call(arguments, 0), i, len;

    // set any values passed to the constructor
    if (args.length === 1 && typeof args[0] === 'number') {
        values = new Array( args[0] );
    } else if(args.length > 0) {
        for (i = 0, len = args.length; i < len; i += 1) {
            values[i] = args[i];
        }
    }

    function callInterceptors(index, newValue) {
        for (var i = 0; i < interceptors.length; i += 1) {
            interceptors[i](index, newValue);
        }
    }

    return {
        get : function (index) {
            // user never has access to the private variable "values"
            return values[index];
        },

        set : function (index, newValue) {
            callInterceptors(index, newValue);
            values[index] = newValue;
        },

        listen : function (fn) {
            if (typeof fn === 'function') {
                interceptors.push(fn);
            }
        },

        get length() {
            return values.length;
        },

        push : function () {
            var args = [].slice.call(arguments, 0), i, len;
            // make .push() call our .set() function
            // so it calls our listeners
            for (i = 0, len = args.length; i < len; i += 1) {
                this.set( this.length, args[i] );
            }
        }
    };
}

var names = new cArray('Jim', 'Bob', 'John');

// add a listener
names.listen(function (index, passedValue) {
    alert('You tried to set [' + index + '] to ' + passedValue);
});

// add another listener
names.listen(function (index, passedValue) {
    alert('AAARRG! Why did you modify [' + index + '] to ' + passedValue + '?!?!');
});

names.set(3, 'Mary');

names.push('Marvin', 'Johnson');

alert('names\' length: ' + names.length);

// --------------------------------
// let's only define the array...