{"id":24641117,"url":"https://github.com/codewithhridoy/javascript-quick-functions","last_synced_at":"2025-03-20T11:49:04.183Z","repository":{"id":170712124,"uuid":"473837872","full_name":"codewithhridoy/javascript-quick-functions","owner":"codewithhridoy","description":null,"archived":false,"fork":false,"pushed_at":"2022-03-25T02:12:10.000Z","size":7,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-25T12:12:16.897Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/codewithhridoy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2022-03-25T02:10:02.000Z","updated_at":"2022-03-25T02:10:02.000Z","dependencies_parsed_at":"2023-08-17T03:58:08.354Z","dependency_job_id":null,"html_url":"https://github.com/codewithhridoy/javascript-quick-functions","commit_stats":null,"previous_names":["hrid0ybd/javascript-quick-functions","codewithhridoy/javascript-quick-functions"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codewithhridoy%2Fjavascript-quick-functions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codewithhridoy%2Fjavascript-quick-functions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codewithhridoy%2Fjavascript-quick-functions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codewithhridoy%2Fjavascript-quick-functions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/codewithhridoy","download_url":"https://codeload.github.com/codewithhridoy/javascript-quick-functions/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244609431,"owners_count":20480782,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-01-25T12:12:18.679Z","updated_at":"2025-03-20T11:49:04.155Z","avatar_url":"https://github.com/codewithhridoy.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Javascript Quick functions\n\nMost of you probably already know them, lodash/underscore was built to provide utility functions for common tasks in Javascript. But some you don’t want to install a package for small use case. So I created this file to provide a quick access to the most used functions. I hope you will find it useful.\n\n### [Demo \u0026 Reference](https://github.com/hrid0ybd/javascript-quick-functions)\n\n---\n\n# Table of contents\n\n[Functions](#functions)\n\n- [Regular function](#regular-function)\n- [Function expression](#function-expression)\n- [Arrow function](#arrow-function)\n- [Generator function](#generator-function)\n- [Time the execution of your code](#time-the-execution-of-your-code)\n- [Evaluate a string](#evaluate-a-string)\n\n[Array](#array)\n\n- [Create an array of numbers from 1 to n](#create-an-array-of-numbers-from-1-to-n)\n- [Create an array of numbers from 1 to n with a step](#create-an-array-of-numbers-from-1-to-n-with-a-step)\n- [Create an array and fill it with a value](#create-an-array-and-fill-it-with-a-value)\n- [Shuffling an array](#shuffling-an-array)\n- [Convert an object into a list of `[key, value]` pairs](#convert-an-object-into-a-list-of-key-value-pairs)\n- [Convert a list of `[key, value]` pairs into an object](#convert-a-list-of-key-value-pairs-into-an-object)\n- [Remove an element from an array](#remove-an-element-from-an-array)\n- [Remove Duplicated from Array](#remove-duplicated-from-array)\n- [Swap variables or values](#swap-variables-or-values)\n\n[Numbers](#numbers)\n\n- [Generate random number](#generate-random-number)\n- [Generate random number with a step](#generate-random-number-with-a-step)\n- [Number is even or not](#number-is-even-or-not)\n- [Number is odd or not](#number-is-odd-or-not)\n- [Find the factorial of a number](#find-the-factorial-of-a-number)\n- [Find the sum of an array](#find-the-sum-of-an-array)\n- [Find median of an array](#find-median-of-an-array)\n- [Find largest numbers](#find-largest-numbers)\n- [Find average of Numbers](#find-average-of-numbers)\n- [Find smallest numbers](#find-smallest-numbers)\n- [Find mode of an array](#find-mode-of-an-array)\n- [Find the range of an array](#find-the-range-of-an-array)\n- [Pick a random element from an array](#pick-a-random-element-from-an-array)\n- [Map an array without .map()](#map-an-array-without-map)\n- [Empty an array without .splice()](#empty-an-array-without-splice)\n- [Convert array to object](#convert-array-to-object)\n- [Find intersection of two arrays](#find-intersection-of-two-arrays)\n- [Remove falsy values from an array](#remove-falsy-values-from-an-array)\n- [Rounding number to N decimal place](#rounding-number-to-n-decimal-place)\n\n[String](#string)\n\n- [Reverse String](#reverse-string)\n- [Find Longest Word in a String](#find-longest-word-in-a-string)\n- [Generate Title Case](#generate-title-case)\n- [Is String Palindrome](#is-string-palindrome)\n- [Copy to Clipboard](#copy-to-clipboard)\n- [Find a vowel in a string](#find-a-vowel-in-a-string)\n- [Email validator](#email-validator)\n- [Validate only character and space](#validate-only-character-and-space)\n- [Validate only number](#validate-only-number)\n- [Casting values in arrays using map](#casting-values-in-arrays-using-map)\n\n[Date \u0026 Object](#date--object)\n\n- [Check object is empty or not](#check-object-is-empty-or-not)\n- [Get the current date](#get-the-current-date)\n- [Find the day of the week](#find-the-day-of-the-week)\n- [Find the day of the year](#find-the-day-of-the-year)\n- [Find the number of days in a month](#find-the-number-of-days-in-a-month)\n- [Find the current month](#find-the-current-month)\n- [Find the number of seconds until midnight](#find-the-number-of-seconds-until-midnight)\n- [Log Time from Date](#log-time-from-date)\n- [Format JSON output with spaces](#format-json-output-with-spaces)\n- [Deep clone an object](#deep-clone-an-object)\n\n[Promises](#promises)\n\n- [Wait for a promise to resolve](#wait-for-a-promise-to-resolve)\n- [Is function async](#is-function-async)\n- [Callback to Promise](#callback-to-promise)\n- [Promise retry](#promise-retry)\n\n[Styling](#styling)\n\n- [Generate a random color](#generate-a-random-color)\n- [Convert to rem](#convert-to-rem)\n- [Styled Components get color from theme](#styled-components-get-color-from-theme)\n\n[Window \u0026 Dom](#window--dom)\n\n- [Get selected text](#get-selected-text)\n\n[Data Structures](#data-structures)\n\n- [Create a stack](#create-a-stack)\n- [Create a queue](#create-a-queue)\n- [Recursion](#recursion)\n- [Memoization (cache)](#memoization-cache)\n\n# Functions\n\n### Regular function\n\n```javascript\nfunction sum(a, b) {\n  return a + b;\n}\n```\n\n### Function expression\n\n```javascript\nconst sum = function (a, b) {\n  return a + b;\n};\n```\n\n### Arrow function\n\n```javascript\nconst sum = (a, b) =\u003e {\n  return a + b;\n};\n// OR\nconst sum = (a, b) =\u003e a + b;\n```\n\n### Generator function\n\n```javascript\nfunction* indexGenerator() {\n  let index = 0;\n  while (true) {\n    yield index++;\n  }\n}\nconst g = indexGenerator();\nconsole.log(g.next().value); // =\u003e 0\nconsole.log(g.next().value); // =\u003e 1\n```\n\n### Time the execution of your code\n\n```javascript\nconsole.time(\"time\");\nfor (let i = 0; i \u003c 1000000; i++) {\n  // do something\n}\nconsole.timeEnd(\"time\"); // time: 0.827ms\n```\n\n### Evaluate a string\n\n```javascript\nconst toJavascript = (str) =\u003e eval(str);\ntoJavascript(\"alert('Hello World')\");\n```\n\n# Array\n\n### Create an array of numbers from 1 to n\n\n```javascript\nconst range = (n) =\u003e Array.from({ length: n }, (_, i) =\u003e i + 1);\nconsole.log(range(10)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n```\n\n### Create an array of numbers from 1 to n with a step\n\n```javascript\nconst range = (n, step = 1) =\u003e Array.from({ length: n }, (_, i) =\u003e i * step);\nconsole.log(range(10, 2)); // [1, 3, 5, 7, 9]\n```\n\n### Create an array and fill it with a value\n\n```javascript\nconst fill = (len, value) =\u003e Array(len).fill(value);\nconsole.log(fill(3, 0)); // [0, 0, 0]\n```\n\n### Shuffling an array\n\n```javascript\nconst shuffleArray = (arr) =\u003e arr.sort(() =\u003e 0.5 - Math.random());\nconsole.log(shuffleArray([1, 2, 3, 4])); // [3, 2, 1, 4]\n```\n\n### Convert an object into a list of `[key, value]` pairs\n\n```javascript\nconst toPairs = (obj) =\u003e Object.entries(obj);\nconsole.log(toPairs({ a: 1, b: 2, c: 3 })); // [['a', 1], ['b', 2], ['c', 3]]\n```\n\n### Convert a list of `[key, value]` pairs into an object\n\n```javascript\nconst fromPairs = (pairs) =\u003e\n  pairs.reduce((a, b) =\u003e ({ ...a, [b[0]]: b[1] }), {});\nconsole.log(\n  fromPairs([\n    [\"a\", 1],\n    [\"b\", 2],\n    [\"c\", 3],\n  ])\n); // { a: 1, b: 2, c: 3 }\n```\n\n### Remove an element from an array\n\n```javascript\nconst removeElement = (arr, element) =\u003e arr.filter((e) =\u003e e !== element);\nconsole.log(removeElement([1, 2, 3, 4], 2)); // [1, 3, 4]\n```\n\n### Remove Duplicated from Array\n\n```javascript\nconst removeDuplicated = (arr) =\u003e [...new Set(arr)];\nconsole.log(removeDuplicated([1, 2, 3, 3, 4, 4, 5, 5, 6])); // Result: [ 1, 2, 3, 4, 5, 6 ]\n\nconst removeDuplicate = (arr) =\u003e\n  Object.values(arr.reduce((a, b) =\u003e (a[b] ? a : { ...a, [b]: b }), {}));\nconsole.log(removeDuplicate([1, 2, 3, 3])); // Result: [ 1, 2, 3, ]\n```\n\n### Swap variables or values\n\n```javascript\nconst swap = (a, b) =\u003e [b, a];\nlet a = 1,\n  b = 2;\n[b, a] = swap(a, b);\nconsole.log(a, b); // 2, 1\n```\n\n# Numbers\n\n### Generate random number\n\n```javascript\nconst random = (min, max) =\u003e Math.floor(Math.random() * (max - min + 1)) + min;\nconsole.log(random(1, 10)); // Result: 1 ~ 10\n```\n\n### Generate random number with a step\n\n```javascript\nconst random = (min, max, step = 1) =\u003e\n  Math.floor(Math.random() * (max - min + 1)) * step + min;\nconsole.log(random(1, 10, 2)); // Result: 1 ~ 10 with step 2\n```\n\n### Number is even or not\n\n```javascript\nconst isEven = (num) =\u003e num % 2 === 0;\nconsole.log(isEven(4)); // true\n```\n\n### Number is odd or not\n\n```javascript\nconst isOdd = (num) =\u003e num % 2 !== 0;\nconsole.log(isOdd(4)); // false\n```\n\n### Find the factorial of a number\n\n```javascript\nconst factorial = (num) =\u003e (num === 0 ? 1 : num * factorial(num - 1));\nconsole.log(factorial(5)); // 120\n```\n\n### Find the sum of an array\n\n```javascript\nconst sum = (arr) =\u003e arr.reduce((a, b) =\u003e a + b, 0);\nconsole.log(sum([1, 2, 3, 4])); // 10\n```\n\n### Find median of an array\n\n```javascript\nconst median = (arr) =\u003e {\n  const mid = Math.floor(arr.length / 2),\n    nums = [...arr].sort((a, b) =\u003e a - b);\n  return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;\n};\nconsole.log(median([1, 2, 3, 4])); // 2.5\n```\n\n### Find largest numbers\n\n```javascript\nconst findLargest = (arr) =\u003e arr.map((subArr) =\u003e Math.max(...subArr));\nconsole.log(\n  findLargest([\n    [4, 5, 1, 3],\n    [13, 27, 18, 26],\n    [32, 35, 37, 39],\n    [1000, 1001, 857, 1],\n  ])\n); // [5, 27, 39, 1001]\n```\n\n### Find average of Numbers\n\n```javascript\nconst findAverage = (arr) =\u003e arr.reduce((a, b) =\u003e a + b, 0) / arr.length;\nconsole.log(findAverage([1, 2, 3, 4])); // 2.5\n```\n\n### Find smallest numbers\n\n```javascript\nconst findSmallest = (arr) =\u003e arr.map((subArr) =\u003e Math.min(...subArr));\nconsole.log(\n  findSmallest([\n    [4, 5, 1, 3],\n    [13, 27, 18, 26],\n    [32, 35, 37, 39],\n    [1000, 1001, 857, 1],\n  ])\n); // [1, 18, 32, 857]\n```\n\n### Find mode of an array\n\n```javascript\nconst mode = (arr) =\u003e {\n  const counts = arr.reduce((a, b) =\u003e {\n    a[b] = (a[b] || 0) + 1;\n    return a;\n  }, {});\n  const maxCount = Math.max(...Object.values(counts));\n  return Object.keys(counts).filter((key) =\u003e counts[key] === maxCount);\n};\nconsole.log(mode([3, \"a\", \"a\", \"a\", 2, 3, \"a\", 3, \"a\", 2, 4, 9, 3])); // ['a']\n```\n\n### Find the range of an array\n\n```javascript\nconst range = (arr) =\u003e Math.max(...arr) - Math.min(...arr);\nconsole.log(range([1, 2, 3, 4])); // 3\n```\n\n### Pick a random element from an array\n\n```javascript\nconst pick = (arr) =\u003e arr[Math.floor(Math.random() * arr.length)];\nconsole.log(pick([1, 2, 3, 4])); // 2\n```\n\n### Map an array without .map()\n\n```javascript\nconst map = (arr, cb) =\u003e Array.from(arr, cb);\nconsole.log(map([1, 2, 3, 4], (n) =\u003e n * 2)); // [2, 4, 6, 8]\n```\n\n### Empty an array without .splice()\n\n```javascript\nconst empty = (arr) =\u003e {\n  arr.length = 0;\n  return arr;\n};\nconsole.log(empty([1, 2, 3, 4])); // []\n```\n\n### Convert array to object\n\n```javascript\nconst toObject = (arr) =\u003e ({ ...arr });\nconsole.log(toObject([\"a\", \"b\"])); // { 0: 'a', 1: 'b' }\n```\n\n### Find intersection of two arrays\n\n```javascript\nconst intersection = (arr1, arr2) =\u003e {\n  const set = new Set(arr1);\n  return arr2.filter((x) =\u003e set.has(x));\n};\nconsole.log(intersection([1, 2, 3], [2, 3, 4])); // [2, 3]\n```\n\n### Remove falsy values from an array\n\n```javascript\nconst compact = (arr) =\u003e arr.filter(Boolean);\nconsole.log(compact([0, 1, false, 2, \"\", 3, \"a\", \"e\" * 23, NaN, \"s\", 34])); // [1, 2, 3, 'a', 's', 34]\n```\n\n### Rounding number to N decimal place\n\n```javascript\nconst round = (num, decimals = 0) =\u003e num.toFixed(decimals);\nconsole.log(round(1.005, 2)); // 1.00\n```\n\n# String\n\n### Reverse String\n\n```javascript\nconst reverseString = (str) =\u003e str.split(\"\").reverse().join(\"\");\nconsole.log(reverseString(\"hello\")); // olleh\n```\n\n### Find Longest Word in a String\n\n```javascript\nconst findLongestWord = (str) =\u003e\n  str.split(\" \").reduce((a, b) =\u003e (a.length \u003e b.length ? a : b));\nconsole.log(findLongestWord(\"The quick brown fox jumped over the lazy dog\")); // jumped\n```\n\n### Generate Title Case\n\n```javascript\nconst titleCase = (str) =\u003e\n  str\n    .split(\" \")\n    .map((word) =\u003e word[0].toUpperCase() + word.slice(1).toLowerCase())\n    .join(\" \");\nconsole.log(titleCase(\"the quick brown fox\")); // The Quick Brown Fox\n```\n\n### Is String Palindrome\n\n```javascript\nconst isPalindrome = (str) =\u003e str === str.split(\"\").reverse().join(\"\");\nconsole.log(isPalindrome(\"madam\")); // true\n```\n\n### Copy to Clipboard\n\n```javascript\nconst copyToClipboard = (text) =\u003e navigator.clipboard.writeText(text);\ncopyToClipboard(\"Hello World\");\n```\n\n### Find a vowel in a string\n\n```javascript\nconst findVowel = (str) =\u003e str.match(/[aeiou]/gi);\nconsole.log(findVowel(\"hello\")); // ['e', 'o']\n```\n\n### Email validator\n\n```javascript\nconst validateEmail = (email) =\u003e {\n    const re = /^(([^\u003c\u003e()\\[\\]\\\\.,;:\\s@\"]+(\\.[^\u003c\u003e()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n    return re.test(String(email).toLowerCase());\n};\nconsole.log(validateEmail('abc@aaa.co'); // true\n```\n\n### Validate only character and space\n\n```javascript\nconst validateName = (name) =\u003e /^[A-Za-z\\s]+$/.test(name);\nconsole.log(validateName(\"abc\")); // true\nconsole.log(validateName(\"123\")); // false\n```\n\n### Validate only number\n\n```javascript\nconst validateNumber = (number) =\u003e /^[0-9]+$/.test(number);\nconsole.log(validateNumber(\"123\")); // true\nconsole.log(validateNumber(\"abc\")); // false\n```\n\n### Casting values in arrays using map\n\n```javascript\nconst castArray = (arr) =\u003e arr.map(Number);\nconsole.log(castArray([\"1\", \"2\", [3]])); // [1, 2, 3]\n```\n\n# Date \u0026 Object\n\n### Check object is empty or not\n\n```javascript\nconst isEmpty = (obj) =\u003e Object.keys(obj).length === 0;\nconsole.log(isEmpty({})); // true\n```\n\n### Get the current date\n\n```javascript\nconst getDate = () =\u003e new Date();\nconsole.log(getDate()); // 2020-05-25T09:57:37.869Z\n```\n\n### Find the day of the week\n\n```javascript\nconst getDayName = (date) =\u003e {\n  const days = [\n    \"Sunday\",\n    \"Monday\",\n    \"Tuesday\",\n    \"Wednesday\",\n    \"Thursday\",\n    \"Friday\",\n    \"Saturday\",\n  ];\n  return days[date.getDay()];\n};\nconsole.log(getDayName(new Date())); // Friday\n```\n\n### Find the day of the year\n\n```javascript\nconst getDayOfYear = (date) =\u003e {\n  const firstDay = new Date(date.getFullYear(), 0, 1);\n  return Math.ceil((date - firstDay) / 86400000);\n};\nconsole.log(getDayOfYear(new Date())); // 182\n```\n\n### Find the number of days in a month\n\n```javascript\nconst getDaysInMonth = (date) =\u003e\n  new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();\nconsole.log(getDaysInMonth(new Date())); // 31\n```\n\n### Find the current month\n\n```javascript\nconst getMonthName = (date) =\u003e {\n  const months = [\n    \"January\",\n    \"February\",\n    \"March\",\n    \"April\",\n    \"May\",\n    \"June\",\n    \"July\",\n    \"August\",\n    \"September\",\n    \"October\",\n    \"November\",\n    \"December\",\n  ];\n  return months[date.getMonth()];\n};\nconsole.log(getMonthName(new Date())); // March\n```\n\n### Find the number of seconds until midnight\n\n```javascript\nconst getSecondsUntilMidnight = (date) =\u003e\n  (24 - date.getHours()) * 60 * 60 +\n  (60 - date.getMinutes()) * 60 +\n  (60 - date.getSeconds());\nconsole.log(getSecondsUntilMidnight(new Date())); // 86400\n```\n\n### Log Time from Date\n\n```javascript\nconst logTime = (date) =\u003e date.toTimeString().slice(0, 8);\nlogTime(new Date()); // 09:57:37\n\nconst logTime = (date) =\u003e date.toLocaleTimeString(\"en-GB\");\nlogTime(new Date()); // 09:57:37\n```\n\n### Format JSON output with spaces\n\n```javascript\nconst formatJSON = (json) =\u003e JSON.stringify(json, null, 2);\nconsole.log(formatJSON({ a: 1, b: 2 }));\n```\n\n### Deep clone an object\n\n```javascript\nconst clone = (obj) =\u003e JSON.parse(JSON.stringify(obj));\nconsole.log(clone({ a: 1, b: 2 })); // { a: 1, b: 2 }\n\n// OR\n\nconst deepCopy = (obj, copy = {}) =\u003e {\n  if (!obj || typeof obj !== \"object\") return obj;\n  for (const key in obj) {\n    if (obj.hasOwnProperty(key)) copy[key] = deepCopy(obj[key]);\n  }\n  return copy;\n};\n```\n\n# Promises\n\n### Wait for a promise to resolve\n\n```javascript\nconst wait = (ms) =\u003e new Promise((resolve) =\u003e setTimeout(resolve, ms));\nwait(1000).then(() =\u003e console.log(\"You'll see this after 1 second\"));\nawait wait(1000); // Next line will be executed after 1 second\n```\n\n### Is function async\n\n```javascript\nconst isAsync = (fn) =\u003e fn.constructor.name === \"AsyncFunction\";\nconsole.log(isAsync(async () =\u003e {})); // true\n```\n\n### Callback to Promise\n\n```javascript\nconst promisify =\n  (fn) =\u003e\n  (...args) =\u003e {\n    return new Promise((res, reject) =\u003e\n      fn(...args, (err, data) =\u003e (err ? reject(err) : res(data)))\n    );\n  };\n```\n\n### Promise retry\n\n```javascript\nconst retry = (fn, times = 3) =\u003e {\n  return (...args) =\u003e\n    new Promise((resolve, reject) =\u003e {\n      const attempt = (n) =\u003e {\n        fn(...args)\n          .then(resolve)\n          .catch((err) =\u003e {\n            if (n === times) return reject(err);\n            attempt(n + 1);\n          });\n      };\n      attempt(1);\n    });\n};\n```\n\n# Styling\n\n### Generate a random color\n\n```javascript\nconst getRandomColor = () =\u003e\n  `#${Math.floor(Math.random() * 16777215).toString(16)}`;\nconsole.log(getRandomColor()); // #f0f0f0\n\nconst randomHex = () =\u003e\n  `#${Math.floor(Math.random() * 0xffffff)\n    .toString(16)\n    .padEnd(6, \"0\")}`;\nconsole.log(randomHex()); // #f0f0f0\n```\n\n### Convert to rem\n\n```javascript\nconst toRem = (px) =\u003e `${px / 16}rem`;\nconsole.log(toRem(16)); // 1rem\n```\n\n### Styled Components get color from theme\n\n```javascript\nOff topic but very useful\n\nconst getPrimaryMain = props =\u003e props.theme.main\n\nconst Button = styled.button`\n    color: ${getPrimaryMain};\n    border: 2px solid ${getPrimaryMain};\n`;\n```\n\n# Window \u0026 Dom\n\n### Get selected text\n\n```javascript\nconst getSelectedText = () =\u003e window.getSelection().toString();\nconsole.log(getSelectedText()); // Hello World\n```\n\n# Data Structures\n\n### Create a stack\n\n```javascript\nconst Stack = () =\u003e {\n  let data = [];\n  return {\n    push(item) {\n      data.push(item);\n    },\n    pop() {\n      return data.pop();\n    },\n    peek() {\n      return data[data.length - 1];\n    },\n    get length() {\n      return data.length;\n    },\n  };\n};\n```\n\n### Create a queue\n\n```javascript\nconst Queue = () =\u003e {\n  let data = [];\n  return {\n    push(item) {\n      data.push(item);\n    },\n    pop() {\n      return data.shift();\n    },\n    peek() {\n      return data[0];\n    },\n    get length() {\n      return data.length;\n    },\n  };\n};\n```\n\n### Recursion\n\n```javascript\nconst range = (n) =\u003e {\n  if (n === 0) return;\n  console.log(n);\n  range(n - 1);\n};\nconsole.log(range(5));\n```\n\n### Memoization (cache)\n\nTry the following code without memo and with memo.\n\n```javascript\nconst fib = (n) =\u003e {\n  if (n \u003c 2) return n;\n  return fib(n - 1, memo) + fib(n - 2, memo);\n};\nconsole.log(fib(40)); // Browser crash or timeout\n\nconst fib = (n, memo = {}) =\u003e {\n  if (n \u003c 2) return n;\n  if (memo[n]) return memo[n];\n  memo[n] = fib(n - 1, memo) + fib(n - 2, memo);\n  return memo[n];\n};\nconsole.log(fib(40)); // 102334155\n```\n\n# Tools used\n\n[Table of contents Builder](https://luciopaiva.com/markdown-toc/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodewithhridoy%2Fjavascript-quick-functions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodewithhridoy%2Fjavascript-quick-functions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodewithhridoy%2Fjavascript-quick-functions/lists"}