Skip to content

Instantly share code, notes, and snippets.

@alessioalex
Created February 3, 2016 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alessioalex/c0562958b112ae7fcccd to your computer and use it in GitHub Desktop.
Save alessioalex/c0562958b112ae7fcccd to your computer and use it in GitHub Desktop.
ES6 Proxy magic for arrays
// https://curiosity-driven.org/array-slices#mimicking-array
function emulateArray(obj) {
var length = obj.length || 0;
return new Proxy(obj, {
get: function(target, property) {
if (property === 'length') {
return length;
}
if (property in target) {
return target[property];
}
if (property in Array.prototype) {
return Array.prototype[property].bind(obj);
}
},
set: function(target, property, value) {
if (property === 'length') {
for (var i = value; i < length; i++) {
delete target[i];
}
length = value;
return;
}
target[property] = value;
if (Number(property) >= length) {
length = Number(property) + 1;
}
}
});
}
var obj = {
0: 17,
1: 29,
2: 51,
length: 3
};
obj = emulateArray(obj);
@alessioalex
Copy link
Author

alessioalex commented Feb 27, 2018

'use strict';

const proxyObject = require('./');

const o = {
  a: [
    1, 2, 3, 4, [ 5, 6, 7]
  ],
  b: {
    c: { d: [1, 2, 3], e: 5 }
  }
};

const obj = proxyObject(o, (path, val, isRemoved) => {
  if (isRemoved) {
    console.log(`removed ${path}`);
  } else {
    console.log(`${path} = `, val);
  }
});

/*
console.log('obj.a[4]:', obj.a[4]);
console.log('obj.a[4].pop()');
obj.a[4].pop();
console.log('delete obj.a[4][1]');
delete obj.a[4][1]
console.log('obj.b.c.d[2] = 222');
obj.b.c.d[2] = 222;
*/

console.log('----------------');
obj.a[3] = { bb: 22, cc: 44 };
// delete obj.a[3].cc;
obj.a[3].bb = { a: 1, b: 2, c: [33, 44] };
// delete obj.a[3].bb.c[1];
console.log('-------push-------');
obj.a[3].bb.c.push(2,3,4);
console.log('-------unshift----');
obj.a[3].bb.c.unshift(0,1,1);
console.log('-------pop--------');
obj.a[3].bb.c.pop();
console.log('-------shift------');
obj.a[3].bb.c.shift();
console.log('------------------');

// obj.c = { b: 2, c: 4 };
// delete obj.c.c;

console.log(obj.a[3].bb.c.length, JSON.stringify(obj));

// console.log('JSON.stringify(obj.a[4]):', JSON.stringify(obj.a[4]));
// console.log('obj.a[4].valueOf():', obj.a[4].valueOf());
// obj2.a[4]
// > Proxy {0: 5, 1: 6, 2: 7, length: 3} << 'hide' length

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment