Skip to content

Instantly share code, notes, and snippets.

@BiosBoy
Created July 31, 2024 06:56
Show Gist options
  • Select an option

  • Save BiosBoy/0c6b2f6ff8e23afe50a7b78f470cb6dc to your computer and use it in GitHub Desktop.

Select an option

Save BiosBoy/0c6b2f6ff8e23afe50a7b78f470cb6dc to your computer and use it in GitHub Desktop.
const map = new Map();
map.set(1, 'Number one');
map.set('1', 'String one');
map.set(true, 'Boolean true');
console.log(map.get(1)); // Output: Number one
const map = new Map();
map.set('a', 1);
map.set('b', 2);
map.set('c', 3);
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
// Output:
// a: 1
// b: 2
// c: 3
const map = new Map();
map.set('a', 1);
map.set('b', 2);
console.log(map.size); // Output: 2
const map = new Map();
map.set('key', 'value');
console.log(map.get('key')); // Output: value
console.log(map.has('key')); // Output: true
map.delete('key');
console.log(map.has('key')); // Output: false
map.clear();
console.log(map.size); // Output: 0
const map = new Map();
map.set('a', 1);
const obj = Object.fromEntries(map);
console.log(JSON.stringify(obj)); // Output: {"a":1}
const objKey = {};
const map = new Map();
map.set(objKey, 'Object as key');
console.log(map.get(objKey)); // Output: Object as key
const user = {
name: 'John Doe',
age: 30,
occupation: 'Developer'
};
function countOccurrences(arr: any[]): Map<any, number> {
const map = new Map();
for (const item of arr) {
map.set(item, (map.get(item) || 0) + 1);
}
return map;
}
const result = countOccurrences([1, 2, 2, 3, 3, 3]);
console.log(result); // Output: Map { 1 => 1, 2 => 2, 3 => 3 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment