Last active
February 21, 2024 11:48
-
-
Save padolsey/8cfb97dfc873a7a51d8eed1116a918dd to your computer and use it in GitHub Desktop.
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
/** | |
* I reckon computed member access in JS, i.e. ...[...], | |
* could be a tonne more powerful. This is an example of that. | |
* =========================================================== | |
* This is a filthy hack. Probably don't use it... | |
* =========================================================== | |
* It sets up a proxy that'll catch member access to arrays. | |
* Upon member-access, toString will be natively called and | |
* intercepted; the intercepted value will be used within our | |
* proxy to return a filtered version of the array. | |
*/ | |
((filterFn, filterArr) => { | |
const aps = Array.prototype.toString, | |
fps = Function.prototype.toString; | |
Function.prototype.toString = function() { | |
return fps.apply(filterFn = this, arguments) }; | |
Array.prototype.toString = function() { | |
return aps.apply(filterArr = this, arguments) }; | |
Object.setPrototypeOf(Array.prototype, new Proxy( | |
{}, { | |
get: function(target, prop, receiver) { | |
return Reflect.get(...arguments) || ( | |
filterFn && prop === fps.call(filterFn) ? | |
receiver.filter(filterFn) : | |
filterArr && prop === aps.call(filterArr) ? | |
filterArr.map(fn => receiver.filter(fn)) | |
: undefined ); | |
} | |
} | |
)); | |
})(); | |
// Filter just those numbers less than 4 | |
[1, 2, 3, 4, 5][ n => n < 4 ]; // => [1, 2, 3] | |
// Filter numbers larger than and less than five into two arrays: | |
[1, 2, 3, 4, 5, 6, 7, 8, 9][[ | |
n => n < 5, | |
n => n > 5 | |
]]; // => [[1, 2, 3, 4], [6, 7, 8, 9]] | |
// More examples..... | |
const [odd, even] = [0, 1, 2, 3, 3, 4, 5, 6][[ | |
n => n % 2, | |
n => !(n % 2) | |
]]; // => [[1, 3, 5], [0, 2, 6]] | |
const [ | |
empty, | |
local, | |
remote | |
] = [...document.querySelectorAll('a')][[ | |
a => !a.href, | |
a => a.hostname === location.hostname, | |
a => a.hostname !== location.hostname | |
]]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment