Freeze Set object

Isabelle Viktoria Maciohsek · JavaScript, Array · Oct 11, 2020

Creates a frozen Set object.

  • Use the Set constructor to create a new Set object from iterable.
  • Set the add, delete and clear methods of the newly created object to undefined, so that they cannot be used, practically freezing the object.
const frozenSet = iterable => {
  const s = new Set(iterable);
  s.add = undefined;
  s.delete = undefined;
  s.clear = undefined;
  return s;
};
frozenSet([1, 2, 3, 1, 2]);
// Set { 1, 2, 3, add: undefined, delete: undefined, clear: undefined }

Recommended snippets

  • Creates an object from an array, using a function to map each value to a key.

  • Creates an object from an array, using the specified key and excluding it from each value.

  • Value frequencies

    JavaScript, Array

    Creates an object with the unique values of an array as keys and their frequencies as the values.