Last active
November 30, 2020 00:24
-
-
Save ryandabler/fbfb05313c4c42168bdc84ea15579b57 to your computer and use it in GitHub Desktop.
Complete example of proxying an array for this article: https://itnext.io/meta-programming-in-javascript-with-proxies-64fa4898070e
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const db = [ | |
{ | |
name: 'John Doe', | |
age: 28, | |
lastModified: Date.now(), | |
lastAccessed: Date.now() | |
}, | |
{ | |
name: 'Jane Smith', | |
age: 30, | |
lastModified: Date.now(), | |
lastAccessed: Date.now() | |
}, | |
{ | |
name: 'Albert Einstein', | |
age: 52, | |
lastModified: Date.now(), | |
lastAccessed: Date.now() | |
} | |
]; | |
const handler = { | |
get(tgt, prop, rcvr) { | |
const _prop = +prop; | |
if (prop in tgt) tgt[prop].lastAccessed = Date.now(); | |
if (Number.isInteger(_prop) && _prop >= 0) | |
return tgt[_prop]; | |
if (Number.isInteger(_prop) && _prop < 0) { | |
const posProp = tgt.length + _prop; | |
if (posProp in tgt) tgt[posProp].lastAccessed = Date.now(); | |
return tgt[posProp]; | |
} | |
if (prop === 'last') return rcvr[-1]; | |
return tgt[prop]; | |
}, | |
set(tgt, prop, val, rcvr) { | |
if (prop === 'sort') { | |
const { by, dir } = val; | |
tgt.sort( | |
(a, b) => dir === 'asc' | |
? (a[by] < b[by] ? -1 : 1) | |
: (b[by] < a[by] ? -1 : 1) | |
); | |
} | |
if (prop === 'new') { | |
tgt.push({ ...val, lastModified: Date.now(), lastAccessed: Date.now() }); | |
} | |
return true; | |
}, | |
has(tgt, prop) { | |
const obj = JSON.parse(prop); | |
const criteria = Object.entries(obj); | |
return tgt.some(obj => | |
criteria.every( ([key, val]) => obj[key] === val ) | |
); | |
}, | |
ownKeys(tgt) { | |
const keys = tgt.reduce( | |
(keys, doc) => { | |
const docKeys = Object.keys(doc); | |
docKeys.forEach(key => { | |
keys.add(key); | |
}); | |
return keys; | |
}, | |
new Set() | |
); | |
return [ ...keys, 'length' ]; | |
}, | |
deleteProperty(tgt, prop) { | |
const keys = this.ownKeys(tgt).slice(0, -1); | |
if (keys.includes(prop)) { | |
tgt.forEach(row => { | |
delete row[prop]; | |
}); | |
return true; | |
} | |
return false; | |
} | |
}; | |
const dbProxy = new Proxy(db, handler); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment