Immutable examples

PHOTO EMBED

Tue Feb 09 2021 07:59:26 GMT+0000 (UTC)

Saved by @noobj

/******** Array  ********/

// Instead of simple assigment
const a = Object.freeze([4, 5, 6]);
const b = [...[4, 5, 6]];

// Instead of: a.push(7, 8, 9);
const b = a.concat(7, 8, 9);
const c = [...a, 3]

// Instead of: a.pop();
const c = a.slice(0, -1);

// Instead of: a.unshift(1, 2, 3);
const d = [1, 2, 3].concat(a);

// Instead of: a.shift();
const e = a.slice(1);

/******** Maps ********/
const map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three']
]);

// Instead of: map.set(4, 'four');
const map2 = new Map([...map, [4, 'four']]);

// Instead of: map.delete(1);
const map3 = new Map([...map].filter(([key]) => key !== 1));

// Instead of: map.clear();
const map4 = new Map();

/******** Sets ********/

const set = new Set(['A', 'B', 'C']);

// Instead of: set.add('D');
const set2 = new Set([...set, 'D']);

// Instead of: set.delete('B');
const set3 = new Set([...set].filter(key => key !== 'B'));

// Instead of: set.clear();
const set4 = new Set();


content_copyCOPY