Category Archives: es6

Proxy - (object always defined)

This uses a proxy to make sure all keys/props of an object are always defined.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
let spec = {
  get: (o, key) => {
    return o[key] != null ? o[key] : o[key] = O();
  },
  set: (o, key, v) => {
    o[key] = v;
  }
};
 
let O = () => {
  return new Proxy({}, spec);  
};
 
let dynamic = O();
dynamic.prop.creation = 'is interesting';
dynamic.prop.stuff.not.clear.what.this.could.be.used.for = 123;
 
// log out full structure
let f = (o) => {
  for (let i in o) {
    console.log(o[i]);
    if (typeof o[i] === 'object') f(o[i]);
  }
};
f(dynamic);

Outputs:

Proxy {creation: "is interesting", stuff: Proxy}
is interesting
Proxy {not: Proxy}
Proxy {clear: Proxy}
Proxy {what: Proxy}
Proxy {this: Proxy}
Proxy {could: Proxy}
Proxy {be: Proxy}
Proxy {used: Proxy}
Proxy {for: 123}
123
Also posted in Object, dynamic, functions, javascript | Tagged , | Leave a comment

es6 concat trick

let a = [1], b = [2], c = [3],
    d = [...a, ...b, ...c];
console.log(d);
// outputs: [1, 2, 3]
Also posted in arrays, javascript | Tagged | Leave a comment

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 Dictionary, arrays, associative arrays, html5, javascript | Tagged , , , | Leave a comment