Category Archives: Dictionary

Dictionary with ES6 Symbol

Creating a dictionary type object with ES6 Symbols is easy. Yes we have Maps and WeakMaps but this is still interesting for a variety of reasons… Being able to use objects as keys in another object (dictionary) has many great uses…. So how do you use Symbols like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let a = { id: Symbol('key') },
    b = { id: Symbol('key') };
 
let dictionary = {
  [a.id]: 'value by obj a',
  [b.id]: 'value by obj b'
};
 
console.log(dictionary[a.id]);
console.log(dictionary[b.id]);
 
// outputs:
// 'value by obj a'
// 'value by obj b'

By using either object a or object b’s `id` symbol, our dictionary points to another value. This old AS3 snippet is similar:

http://actionsnippet.com/?p=426

Also posted in arrays, associative arrays, es6, html5, javascript | Tagged , , , | Leave a comment

Dynamic Vars Dictionary

Actionscript:
  1. var vars:Dictionary = new Dictionary();
  2.  
  3. var sp:Sprite = new Sprite();
  4.  
  5. // associate variables with a sprite (or any non-dynamic class)
  6. vars[sp] = {posX:100, posY:100, velX:1, velY:1};
  7.  
  8. // read
  9. trace(vars[sp].posX);

I've heard people mention that they wish the sprite class were dynamic... meaning they wish they could add methods and properties to a Sprite instance at runtime. There's no way I know of to do this, however... the dictionary class can be used to associate variables with any non-dynamic class instance... as it does in this the above example.

The dictionary class is similar to an associative array except that instead of using strings for keys, dictionaries use object instances.

Also posted in arrays, dynamic | Tagged , | 1 Comment