Well-Known Symbols: Array item getter/setter

Jordan Harband ljharb at gmail.com
Thu Apr 9 18:37:03 UTC 2015


One advantage of this approach is that more "spec magic" can be implemented
in terms of the language - it would also make subclassed arrays more
versatile instead of having to always be a Proxy.

On Thu, Apr 9, 2015 at 11:35 AM, Axel Rauschmayer <axel at rauschma.de> wrote:

> Proxies should be enough for this. Is there any reason not to use them?
>
> On 09 Apr 2015, at 20:31, Kos Ddsky <kosich at gmail.com> wrote:
>
> ( note: you can view this message as a gist @ https://gist.github.com/kosich/375da99403c76bc75bbd )
>
> Currently we can imitate Arrays only with objects, where we would refer to a value at some position via referring to objects property ( with integer index being converted to a string )
>
> ```js
> var arr = {
>   "0" : "zero",
>   "1" : "one"
> };
>
> arr[ 1 ];
> ```
> But we wouldn't get all those features that original Array has (like length autoincremention, splice, split etc.)
>
> So, the suggestion is to have WKS for getting and setting item in array by index.
>
> ```js
> get [ Symbol.Array.item ] ( index ){ /*returning code here*/  }
> set [ Symbol.Array.item ] ( index ){ /*setter code here*/ }
> ```
>
> -or-
>
> ```js
> [ Symbol.Array.get ] ( index ){ /*returning code here*/ }
> [ Symbol.Array.set ] ( index ){ /*setter code here*/ }
> ```
>
> ## Possible usecases
>
> ### readonly array
> will throw if user tries to set item directly via index
> ```js
> class ROArray extends Array {
>
>   constructor( initialValues ){
>     // init the array values here
>   }
>
>   [ Symbol.Array.set ] ( index ){
>     throw 'can`t set';
>   }
>
>   [ Symbol.Array.get ] ( index ){
>     return this[ index ];
>   }
>
> }
> ```
>
> ### template-like behavior
> items getter will wrap the value into a tag
> ```js
> class LITemplateArray extends Array {
>
>   set tag ( tag ){
>     this._tag  = tag;
>   }
>
>   [ Symbol.Array.get ] ( index ){
>     var tag = this._tag || 'li',
>           value = this[ index ];
>
>     return `<${ tag }>${value}</${tag}>`;
>   }
>
> }
> ```
>
> /*this is my first thread here, so I'm sorry if being wrong somewhere*/
> /*after googling around, I haven't found such suggestion. though could easily miss that*/
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
> --
> Dr. Axel Rauschmayer
> axel at rauschma.de
> rauschma.de
>
>
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150409/d0b15f8b/attachment-0001.html>


More information about the es-discuss mailing list