Javascript has no real Set or Dictionary implementation, which for someone spoiled by python’s set and dicts is rather frustrating. However, in leiu of the poorly supported js Set type, plain old objects can be massaged into acting as both sets and dicts:


// Python: d = dict()
var d = {};

// d['key'] = 'value'
d['key'] = 'value';

// d.get('nonexistent', 'fallback')
d.hasOwnProperty('nonexistent') ? d['nonexistent'] : 'fallback';

// d.keys()
Object.keys(d);

// s = set()
var s = {};

// s.add(1)
s[1] = true;

// 1 in s
s.hasOwnProperty(1);

// Accessing all values in set:
Object.keys(s);

Notes: the in operator can be used to test membership, but will incorrectly return true for __proto__, as well as all properties up the prototype chain, i.e. all properties and methods of Object. hasOwnProperty is much safer to use.

Similarly, the use of the ternary operator for get-item-with-fallback could in theory be replaced with d['item'] || 'fallback', unless of course the value stored was falsey, in which case the or will incorrectly return a truthier fallback.

— 2 likes