Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vectorized .all method on arrays to transparently access all members
Object.defineProperty(Array.prototype, 'all', {
get: function () {
return new Proxy(this, {
get: function(target, name, receiver) {
return target.map(x => x[name]);
},
set: function (target, name, value) {
target.forEach(x => x[name] = value);
},
// ... call:, etc.
});
},
});
/// EXAMPLE:
var a = [
{x: 1},
{x: 2},
{x: 3}
];
console.log(a.all.x.join(', '));
//a.all.x *= 10; -- doesn't work because:
// <=> a.all.x = a.all.x * 10;
// <=> a.all.x = [1, 2, 3] * 10;
// <=> a.all.x = NaN;
a.all.x = 10;
console.log(a.all.x.join(', '));
// Copyright © 2016 Hraban Luyat <hraban@0brg.net>
// Licensed under CC0 ("public domain")
// see: https://creativecommons.org/publicdomain/zero/1.0/
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.