Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Experimenting with JavaScript Proxy
const EventEmitter = require("events");
const _ = require("lodash");
const timestamp = function () {
const now = new Date();
return new Date(now.getTime() + now.getTimezoneOffset() * 60000);
};
const ArrayProxy = function (array = [], keys = []) {
const emitter = new EventEmitter();
const hasKeys = !!keys.length;
const predicate = hasKeys ? (...args) => keys.map(key => _.isEqual(...args.map(a => _.result(a, key)))).every(a => a) : _.isEqual;
const defineProperty = function (target, key, descriptor) {
if (key !== "length") {
const { value } = descriptor;
const index = target.findIndex(a => predicate(a, value));
const found = target[index];
const event = { value, type: "change", time: timestamp() };
if (hasKeys && !_.isEmpty(found)) {
if (!_.isEqual(found, value)) {
target[index.toString()] = value;
}
} else {
event.type = "insert";
target[key] = value;
}
emitter.emit(event.type, event);
}
target.length = target.filter(a => !!a).length;
return true;
};
const deleteProperty = function (target, key) {
const value = target[key];
const event = { value, type: "delete", time: timestamp() };
delete target[key];
emitter.emit(event.type, event);
return true;
};
const properties = {
on: { value: (...args) => emitter.on(...args) }, off: { value: (...args) => emitter.off(...args) }
};
return new Proxy(Object.defineProperties(array, properties), { defineProperty, deleteProperty });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.