Skip to content

Instantly share code, notes, and snippets.

@kosich
Last active August 29, 2015 14:18
Show Gist options
  • Save kosich/375da99403c76bc75bbd to your computer and use it in GitHub Desktop.
Save kosich/375da99403c76bc75bbd to your computer and use it in GitHub Desktop.
Well-Known Symbols: array item getter/setter

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 )

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.

get [ Symbol.Array.item ] ( index ){ /*returning code here*/  }
set [ Symbol.Array.item ] ( index ){ /*setter code here*/ }

-or-

[ 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

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

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment