Cheatsheet
Overview

Anagram

anagram.js
const areAnagrams = (A, B) =>
  A.split('').sort().join('') ===
  B.split('').sort().join('');
console.log(areAnagrams('listen',
'silent'));

Bind Polyfill

bindPolyfill.js
let person = {
  first: 'sarthak',
  last: 'bansal',
};

function printNames(hometown, country) {
  console.log(this.first + this.last + hometown + country);
}

Function.prototype.mybind = function (...args) {
  let obj = this;
  return function (...args2) {
    obj.call(...args, ...args2);
  };
};

let print2 = printNames.mybind(person, 'delhi');
print2('india');

Capitalize Words

capitalize.js
function capitalize(str) {
  if (!str) return "";
  let result = str[0].toUpperCase();
  for (let i = 1; i < str.length; i++) {
    if (str[i - 1] === ' ') {
      result += str[i].toUpperCase();
    } else {
      result += str[i];
    }
  }
  return result;
}

console.log(capitalize("the boy is hungry"));

Factorial Memoization

factorial.js
// Factorial with memoization
function _fac() {
  let result = {};
  return function fac(n) {
    if (n < 0) {
      throw new Error("Factorial is not defined for negative numbers");
    }
    if (n <= 1) {
      return 1;
    }
    if (result[n]) {
      return result[n];
    }
    result[n] = n * fac(n - 1);
    return result[n];
  };
}
let fac = _fac();
console.log(fac(10));

Fibonacci Memoization

fibonacci.js
function memo() {
  let result = {};

  return function fib(n) {
    if (n <= 1) {
      return n;
    } else if (n in result) {
      return result[n];
    } else {
      result[n] = fib(n - 2) + fib(n - 1);
    }

    return result[n];
  };
}
let fib = memo();
console.log(fib(12));

Filter Polyfill

filterPolyfill.js
let arr = [1, 2, 3, 4, 5];
// polyfill below
Array.prototype.myfilter = function (cb) {
  let newarr = [];
  for (let i = 0; i < this.length; i++) {
    if (cb(this[i], i, this)) {
      newarr.push(this[i]);
    }
  }
  return newarr;
};
let arr3 = arr.myfilter((val) => val > 2);
console.log(arr3);

Array.flat Polyfill

flatPolyfill.js
/* eslint-disable no-extend-native */
let arr = [1, 2, [[3, 4]]];
//polyfill
Array.prototype.myflat = function (depth) {
  // If no depth is specified, default to 1
  if (depth === undefined) {
    depth = Infinity;
  }
  // Recursively reduce sub-arrays to the specified depth
  var flatten = function (arr, depth) {
    // If depth is 0, return the array as-is
    if (depth < 1) {
      return arr.slice();
    }
    // Otherwise, concatenate into the parent array
    return arr.reduce(function (acc, val) {
      return acc.concat(Array.isArray(val) ? flatten(val, depth - 1) : val);
    }, []);
  };
  return flatten(this, depth);
};

console.log(arr.myflat());

Generic Memoization

genericMemo.js
function memoize(func) {
  const cache = {};
  return (a, b) => func(cache, a, b);
}
function sum(cache, a, b) {
  const key1 = `${a},${b}`;
  const key2 = `${b},${a}`;
  if (key1 in cache || key2 in cache) {
    console.log("Fetching from memo");
    return key1 in cache ? cache[key1] : cache[key2];
  }
  cache[key1] = a + b;
  console.log(cache);
  return cache[key1];
}

let calculate = memoize(sum);
console.log(calculate(1, 2));
console.log(calculate(1, 2));

Infinite Currying

infinitecurrying.js
const sum = function (a) {
  return function (b) {
    if (b !== undefined) {
      return sum(a + b);
    }
    return a;
  };
};

console.log(sum(1)(2)(3)(4)());

Max Frequency Char

maxChar.js
function maxChar(str) {
  const charMap = {};
  let max = 0;
  let mostFrequentChar = '';
  for (let char of str) {
    charMap[char] = charMap[char] + 1 || 1;
  }

  for (let char in charMap) {
    if (charMap[char] > max) {
      max = charMap[char];
      mostFrequentChar = char;
    }
  }
  return mostFrequentChar;
}

console.log(maxChar("hello"));

Output Question

output.js
(console.log(1) < console.log(2) < console.log(3)) // true

Palindrome

palindrome.js
//palindrome

function palindrome(str) {
  for (let i = 0; i < str.length / 2; i++) {
    if (str[i] !== str[str.length - i - 1]) {
      return false;
    }
  }
  return true;
}

console.log(palindrome("radar"));

Pangram

pangram.js
// Pangram

function isPangram(str) {
  str = str.toLowerCase();
  const alphabets = "abcdefghijklmnopqrstuvwxyz".split("");
  let isPangram = true;
  alphabets.forEach((i) => {
    if (str.indexOf(i) < 0) {
      isPangram = false;
    }
  });
  return isPangram;
}

console.log(isPangram("The quick brown fox jumps over the lazy dog"));

Print Names by Age

printNames.js
const users = [
  { id: 1, name: "Jack", age: 55, isActive: true },
  { id: 2, name: "John", age: 28, isActive: true },
  { id: 3, name: "Mike", age: 20, isActive: false }
];
console.log(
  users
    .sort((a, b) => (a.age > b.age ? 1 : -1))
    .filter((i) => i.isActive)
    .map((i) => i.name)
);

Promise.all Polyfill

promiseAllPolyfill.js
// Promise.all polyfill
let myPromiseAll = (promises) => {
  let responses = new Array(promises.length);
  let resolvedCount = 0;

  if (!Array.isArray(promises)) {
    return Promise.reject(new TypeError("Argument must be an array"));
  }

  return new Promise((resolve, reject) => {
    if (promises.length === 0) {
      resolve([]);
      return;
    }

    promises.forEach((singlePromise, i) => {
      Promise.resolve(singlePromise)
        .then((res) => {
          responses[i] = res; // preserve input order
          resolvedCount++;
          if (resolvedCount === promises.length) {
            resolve(responses);
          }
        })
        .catch((err) => {
          reject(err); // reject immediately on first failure
        }
    });
  });
};

let p1 = Promise.resolve("Promise1");

let p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise 2");
  }, 1000);
});

myPromiseAll([p1, p2]).then(
  (res) => {
    console.log("Response => ", res);

  },
  (err) => {
    console.log("error =>", err);
  }
);

Range Creator

rangeCreator.js
// array range creator
function createRange(start, end) {
  let range = [];
  // return [...Array(end - start + 1).keys()].map((i) => i + start);
  for (let i = start; i <= end; i++) {
    range.push(i);
  }
  return range;
}

console.log(createRange(1, 50));

Remove Duplicates

removeDuplicate.js
//remove duplicate in Array
let arr = [1,2,3,4,2,4,"hello" ,"hello"];
let newarr=[];

arr.forEach((i)=>{
if(newarr.indexOf(i)<0){
  newarr.push(i);
}
});

console.log(newarr);

Reverse String

reverse.js
// method 1
function ReverseString(str) {
  return str.split('').reverse().join('')
}
//method 2
function reverse(str) {
  let reversed = '';
  for(let i of str ) {
    reversed = i + reversed;
  }
  return reversed;
}
console.log(reverse("bye sarthak"))

Array.reverse Polyfill

reversePolyfill.js
var arr = [1, 2, 3, 4];

Array.prototype.myreverse = function () {
  let left = 0;
  let right = this.length - 1;

  while (left < right) {
    [this[left], this[right]] = [this[right], this[left]];
    left++;
    right--;
  }
  return this; // native reverse returns the same mutated array
};

console.log(arr.myreverse());

Search with Filter

search.js
// HTML
<input onkeyup="myFunction(event)" >

<ul id="myUL">
  <li>Apple</li>
  <li>Apricots</li>
  <li>Avocado</li>
  <li>Banana</li>
  <li>kiwi</li>
</ul>

// JS
function myFunction(e) {
  const li = document.getElementsByTagName("li");

  for (let i of li) {
    if (i.innerText.toUpperCase().indexOf(e.target.value.toUpperCase()) > -1) {
      i.style.display = "";
    } else {
      i.style.display = "none";
    }
  }
}

Shuffle Array

shuffle.js
//Shuffle array function
let arr = [1, 2, 3, "hello", 5, 6];

function Shuffle(array) {
  for (let i = 0; i < array.length; i++) {
    let j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}
console.log(Shuffle(arr));

Sorting

sorting.js
let arr = [1, 5, 7, 4, 8, 2];

for (let i = 0; i < arr.length; i++) {
  for (let j = i + 1; j < arr.length; j++) {
    if (arr[i] > arr[j]) {
      const temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    }
  }
}
console.log(arr);

Memoized Sum

sum.js
function memoize() {
  const result = {};
  return function sum(a, b) {
    const key = `${a},${b}`;
    if (key in result) {
      console.log("Fetching from cache");
      return result[key];
    }
    result[key] = a + b;
    console.log(result);
    return result[key];
  };
}
let sum = memoize();
console.log(sum(1, 2));
console.log(sum(1, 2));

Table Generation (DOM)

tableDOM.js
// creates a <table> element and a <tbody> element
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");

// creating all cells
for (let i = 0; i < 2; i++) {
  // creates a table row
  const row = document.createElement("tr");

  for (let j = 0; j < 2; j++) {
    // Create a <td> element and a text node, make the text
    // node the contents of the <td>, and put the <td> at
    // the end of the table row
    const cell = document.createElement("td");
    const cellText = document.createTextNode(i + ", " + j);
    cell.appendChild(cellText);
    row.appendChild(cell);
  }
  // add the row to the end of the table body
  tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
document.body.appendChild(tbl);
// sets the border attribute of tbl to '2'
tbl.setAttribute("border", "2");

Two Sum

twoSum.js
var twoSum = function (nums, target) {
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] + nums[j] === target) return [i, j];
    }
  }
  return [0, 0];
};

console.log(twoSum([1, 2, 3, 4], 3));

Count Vowels

vowels.js
//Count vowels in string

function CountVowels(str) {
  let vowels = ["a", "e", "i", "o", "u"];
  let count = 0;
  str.toLowerCase().split("").forEach((i) => {
    if (vowels.indexOf(i) > -1) {
      count += 1;
    }
  });
  return count;
}

console.log(CountVowels("hello Sarthak"));