Last active
November 10, 2016 15:12
-
-
Save hraban/fa010f536fe46fb1e32f2bde1a90e5ef to your computer and use it in GitHub Desktop.
Vectorized .all method on arrays to transparently access all members
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
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