Polyglot CheatSheet - Map/Dict/Object

Updated: 2018-06-26

Create: Literal

Hack

$d = dict['foo' => 1];

Ruby

>> fruit = { 'a' => 'apple', 'b' => 'banana', 'c' => 'coconut' }
=> {"a"=>"apple", "b"=>"banana", "c"=>"coconut"}

symbol

>> dimensions = { width: 1000, height: 2250, depth: 250 }
=> {:width=>1000, :height=>2250, :depth=>250}

Create: From Existing Collection

Hack

$d = dict($keyed_container);

Default Value

Get Or Else(Default)

Javascript

> a = {}
{}
> a['key']
undefined
> a['key'] || 0
0

Python

Normal dict:

a = {}
a.get('key', 0)

defaultdict: will "default" a value if that key has not been set yet.

>>> import collections
>>> d = collections.defaultdict(lambda: 1)
>>> d
defaultdict(<function <lambda> at 0x104c64f28>, {})
>>> d[1]
1

No default lambda provided will throw exception

>>> c = collections.defaultdict()
>>> c[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1

Here lambda: 1 is the same as the parameterless function f that does this

def f():
  return 1

Clone

let clone = Object.assign({}, obj);

Get

Ruby

>> fruit['b']
=> "banana"

Symbol:

>> dimensions[:depth]
=> 250

Set

Ruby

>> fruit['d'] = 'date'
=> "date"

Add Element

Hack

$d['baz'] = 2;

Remove Element

Hack

unset($d['baz']);

Contains Key

Hack

C\contains_key($d, 'foo')

Contains Value

Hack

C\contains($d, 2)

Count Elements

Hack

C\count($d)

Type Signature

Hack

dict<TKey, TValue>

Type of

Hack

is_dict($d)

Get Keys

Python

Get keys of a dict:

d.keys()

Javascript

Object.keys(obj);

Java

Map<Integer, String> map = new HashMap<>();

List<Integer> result = map.entrySet().stream()
    .map(x -> x.getKey())
    .collect(Collectors.toList());

Hack

Map

$m->keys()

Hack Arrays dict:

Vec\keys($dict)

Get Values

Hack

$vec = vec($dict);

Convert To Other Collections

dict to Map

new Map($d)

dict to array

Arrays::fromDict($d)

dict keys to Vector

Vector::fromKeysOf($d)

dict keys to Set

Set::fromKeysOf($d)

dict keys to array

array_keys($d)

dict values to Vector

new Vector($d)

dict values to Set

new Set($d)

dict values to array

array_values($d)

Construct

Javascript

Object Spread Properties

var a = 1,
  b = 2,
  c = 3;
var x = { x: 4, y: 5, z: 6 };

var obj = { a, b, c, ...x };

console.log(obj); //{a: 1, b: 2, c: 3, x: 4, y: 5, z: 6};

Object Spread is "last one in wins"

> a = {b : 1, c: 2}
{b: 1, c: 2}
> x = {y : 3, z : 4, c: 5}
{y: 3, z: 4, c: 5}
> n = {...a, ...x}
{b: 1, c: 5, y: 3, z: 4}

Destructuring

Javascript

const { children, location } = this.props;

Object Rest Properties

var { a, b, c, ...x } = { a: 1, b: 2, c: 3, x: 4, y: 5, z: 6 };

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

console.log(x); // { x: 4, y: 5, z: 6 }

Iteration

Hack

$dict = dict[];
...
foreach ($dict as $key => $value) {
  ...
}