Skip to content

Instantly share code, notes, and snippets.

@hraban
Last active November 10, 2016 15:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hraban/fa010f536fe46fb1e32f2bde1a90e5ef to your computer and use it in GitHub Desktop.
Save hraban/fa010f536fe46fb1e32f2bde1a90e5ef to your computer and use it in GitHub Desktop.
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