Extras Notebook

JavaScript Extras & Utility Snippets

This notebook contains a collection of miscellaneous JavaScript utility functions, clever snippets, and "good to know" logic that doesn't fit into a single category but is immensely useful in day-to-day development and coding challenges.

IN [ ]
const isAlnum = str => /^[a-z0-9]+$/i.test(str);

console.log(isAlnum("atfg076HKHG(*8")); // false
console.log(isAlnum("atfg076HKHG8"));   // true
IN [ ]
const mapCounterHandler = {
  get(target, key){
    target.has(key) ? target.get(key) : target.set(key, 0);
    return target.get(key)
  },
  set(target, key, value) {
    return target.set(key, value);
  }
};

var topKFrequent = function(nums, k) {
  const map = new Map();
  const tally = new Proxy(map, mapCounterHandler);

  nums.forEach(num => {
    tally[num] += 1;
  });

  return [...map.entries()]
    .sort((a, b) => b[1] - a[1])
    .slice(0, k)
    .map(([num]) => num);
};

console.log(topKFrequent([1,1,1,2,2,3,9,9,9,9,9], 2)); // [9,1]
IN [ ]
// Memoization
const memoize = fn => {
  const cache = new Map()
  return (...args) => {
    const key = JSON.stringify(args)
    if (cache.has(key)) return cache.get(key)
    const res = fn(...args)
    cache.set(key, res)
    return res
  }
}

// USAGE:
const memoFib = (() => {
  const cache = {}
  const f = n => cache[n] ?? (cache[n] = n < 2 ? n : f(n-1)+f(n-2))
  return f
})()

const fibo = memoize(memoFib)
console.log(fibo(10))
IN [ ]
// Binary / decimal conversion
(10).toString(2)   // "1010"
parseInt("1010", 2) // 10
IN [ ]
// swap variables
let a = 2;
let b = 3;
[a, b] = [b, a];
console.log(a, b); // Output: 3 2

// lways safe start of a statement with ; otherwise it will consider it as a continuation of the previous statement
;[a,b]=[b,a];
console.log(a, b); // Output: 3 2