{"id":9317,"date":"2022-04-28T20:43:00","date_gmt":"2022-04-28T18:43:00","guid":{"rendered":"https:\/\/monodes.com\/predaelli\/?p=9317"},"modified":"2022-04-28T10:45:27","modified_gmt":"2022-04-28T08:45:27","slug":"7-more-killer-one-liners-in-javascript-by-tapajyoti-bose-apr-2022-medium","status":"publish","type":"post","link":"https:\/\/monodes.com\/predaelli\/2022\/04\/28\/7-more-killer-one-liners-in-javascript-by-tapajyoti-bose-apr-2022-medium\/","title":{"rendered":"7 More Killer One-Liners in JavaScript | by Tapajyoti Bose | Apr, 2022 | Medium"},"content":{"rendered":"<p><em><a href=\"https:\/\/tapajyoti-bose.medium.com\/7-more-killer-one-liners-in-javascript-1cd180d82695\">7 More Killer One-Liners in JavaScript | by Tapajyoti Bose | Apr, 2022 | Medium<\/a><\/em><\/p>\n<p><!--more--><!--nextpage--><\/p>\n<blockquote>\n<p id=\"ab7c\" class=\"pw-post-body-paragraph kp kq jh kr b ks kt ku kv kw kx ky kz la lb lc ld le lf lg lh li lj lk ll lm ja fn\" data-selectable-paragraph=\"\">This is a continuation of the <a class=\"au ln\" href=\"https:\/\/tapajyoti-bose.medium.com\/7-killer-one-liners-in-javascript-33db6798f5bf\" rel=\"noopener\">previous list of <strong class=\"kr ji\">JavaScript<\/strong> one-liners<\/a>. If you haven\u2019t checked out the article, you are highly encouraged to accomplish so.<\/p>\n<p id=\"7b46\" class=\"pw-post-body-paragraph kp kq jh kr b ks kt ku kv kw kx ky kz la lb lc ld le lf lg lh li lj lk ll lm ja fn\" data-selectable-paragraph=\"\">Let\u2019s crack on with the new list!<\/p>\n<h1 id=\"87f0\" class=\"lt lu jh bn lv lw lx ly lz ma mb mc md me mf mg mh mi mj mk ml mm mn mo mp mq fn\" data-selectable-paragraph=\"\">1. Sleep Function<\/h1>\n<p id=\"a8d9\" class=\"pw-post-body-paragraph kp kq jh kr b ks mr ku kv kw ms ky kz la mt lc ld le mu lg lh li mv lk ll lm ja fn\" data-selectable-paragraph=\"\"><strong class=\"kr ji\">JavaScript<\/strong> has <strong class=\"kr ji\">NO<\/strong> built-in <code class=\"\" data-line=\"\">sleep<\/code> function to wait for a given duration before continuing the execution flow of the code.<\/p>\n<p id=\"69dc\" class=\"pw-post-body-paragraph kp kq jh kr b ks kt ku kv kw kx ky kz la lb lc ld le lf lg lh li lj lk ll lm ja fn\" data-selectable-paragraph=\"\">Luckily, generating a function for this purpose is straightforward<\/p>\n<pre class=\"lp lq lr ls ha na fe nb\"><span id=\"efc0\" class=\"fn nc lu jh mz b do nd ne l nf\" data-selectable-paragraph=\"\">const sleep = (ms) =&gt; new Promise((resolve) =&gt; setTimeout(resolve, ms));<\/span><\/pre>\n<h1 id=\"e31f\" class=\"lt lu jh bn lv lw lx ly lz ma mb mc md me mf mg mh mi mj mk ml mm mn mo mp mq fn\" data-selectable-paragraph=\"\">2. Go Back to the Previous Page<\/h1>\n<p id=\"1abc\" class=\"pw-post-body-paragraph kp kq jh kr b ks mr ku kv kw ms ky kz la mt lc ld le mu lg lh li mv lk ll lm ja fn\" data-selectable-paragraph=\"\">Need to send the user back to the page they came from? <code class=\"\" data-line=\"\">history<\/code> object to the rescue!<\/p>\n<pre class=\"lp lq lr ls ha na fe nb\"><span id=\"3f0e\" class=\"fn nc lu jh mz b do nd ne l nf\" data-selectable-paragraph=\"\">const navigateBack = () =&gt; history.back();\n<em class=\"ng\">\/\/ Or<\/em>\nconst navigateBack = () =&gt; history.go(-1);<\/span><\/pre>\n<h1 id=\"6cba\" class=\"lt lu jh bn lv lw lx ly lz ma mb mc md me mf mg mh mi mj mk ml mm mn mo mp mq fn\" data-selectable-paragraph=\"\">3. Compare Objects<\/h1>\n<p id=\"fc1c\" class=\"pw-post-body-paragraph kp kq jh kr b ks mr ku kv kw ms ky kz la mt lc ld le mu lg lh li mv lk ll lm ja fn\" data-selectable-paragraph=\"\"><strong class=\"kr ji\">Javascript<\/strong> behaves in mysterious ways when comparing objects. Comparing objects with the <code class=\"\" data-line=\"\">===<\/code> operator checks only the <strong class=\"kr ji\">reference of the objects<\/strong>, so the following code always returns <code class=\"\" data-line=\"\">false<\/code>:<\/p>\n<pre class=\"lp lq lr ls ha na fe nb\"><span id=\"0ab5\" class=\"fn nc lu jh mz b do nd ne l nf\" data-selectable-paragraph=\"\">const obj1 = { a: 1, b: 2 };\nconst obj2 = { a: 1, b: 2 };\nobj1 === obj2; <em class=\"ng\">\/\/ false<\/em><\/span><\/pre>\n<p id=\"3d8a\" class=\"pw-post-body-paragraph kp kq jh kr b ks kt ku kv kw kx ky kz la lb lc ld le lf lg lh li lj lk ll lm ja fn\" data-selectable-paragraph=\"\">To solve this very issue, you can create a <strong class=\"kr ji\">deep comparison<\/strong> function:<\/p>\n<pre class=\"lp lq lr ls ha na fe nb\"><span id=\"98f7\" class=\"fn nc lu jh mz b do nd ne l nf\" data-selectable-paragraph=\"\">const isEqual = (a, b) =&gt; JSON.stringify(a) === JSON.stringify(b);<\/span><span id=\"337e\" class=\"fn nc lu jh mz b do nh ni nj nk nl ne l nf\" data-selectable-paragraph=\"\"><em class=\"ng\">\/\/ examples<\/em>\nisEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); <em class=\"ng\">\/\/ true<\/em>\nisEqual({ a: 1, b: 2 }, { a: 1, b: 3 }); <em class=\"ng\">\/\/ false<\/em><\/span><span id=\"1538\" class=\"fn nc lu jh mz b do nh ni nj nk nl ne l nf\" data-selectable-paragraph=\"\"><em class=\"ng\">\/\/ works with arrays too<\/em>\nisEqual([1, 2, 3], [1, 2, 3]); <em class=\"ng\">\/\/ true<\/em>\nisEqual([1, 2, 3], [1, 2, 4]); <em class=\"ng\">\/\/ false<\/em><\/span><\/pre>\n<h1 id=\"b998\" class=\"lt lu jh bn lv lw lx ly lz ma mb mc md me mf mg mh mi mj mk ml mm mn mo mp mq fn\" data-selectable-paragraph=\"\">4. Generate Random id<\/h1>\n<p id=\"05b4\" class=\"pw-post-body-paragraph kp kq jh kr b ks mr ku kv kw ms ky kz la mt lc ld le mu lg lh li mv lk ll lm ja fn\" data-selectable-paragraph=\"\">Need multiple <strong class=\"kr ji\">unique identifiers<\/strong> but not looking to add the <code class=\"\" data-line=\"\">uuid<\/code> package? Try out this simple utility function:<\/p>\n<pre class=\"lp lq lr ls ha na fe nb\"><span id=\"3bed\" class=\"fn nc lu jh mz b do nd ne l nf\" data-selectable-paragraph=\"\">const uuid = () =&gt;\n  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(\/[018]\/g, (c) =&gt;\n    (\n      c ^\n      (crypto.getRandomValues(new Uint8Array(1))[0] &amp; (15 &gt;&gt; (c \/ 4)))\n    ).toString(16)\n  );<\/span><\/pre>\n<p id=\"fdf7\" class=\"pw-post-body-paragraph kp kq jh kr b ks kt ku kv kw kx ky kz la lb lc ld le lf lg lh li lj lk ll lm ja fn\" data-selectable-paragraph=\"\"><strong class=\"kr ji\">NOTE:<\/strong> The function is a <strong class=\"kr ji\">one-liner<\/strong>, but spread across multiple lines for readability.<\/p>\n<h1 id=\"710a\" class=\"lt lu jh bn lv lw lx ly lz ma mb mc md me mf mg mh mi mj mk ml mm mn mo mp mq fn\" data-selectable-paragraph=\"\">5. Get Selected Text<\/h1>\n<p id=\"e0e7\" class=\"pw-post-body-paragraph kp kq jh kr b ks mr ku kv kw ms ky kz la mt lc ld le mu lg lh li mv lk ll lm ja fn\" data-selectable-paragraph=\"\">Want to have access to <strong class=\"kr ji\">the text user selects<\/strong>? <code class=\"\" data-line=\"\">window<\/code> just has a method to help you out!<\/p>\n<pre class=\"lp lq lr ls ha na fe nb\"><span id=\"ffef\" class=\"fn nc lu jh mz b do nd ne l nf\" data-selectable-paragraph=\"\">const getSelectedText = () =&gt; window.getSelection().toString();<\/span><\/pre>\n<h1 id=\"813c\" class=\"lt lu jh bn lv lw lx ly lz ma mb mc md me mf mg mh mi mj mk ml mm mn mo mp mq fn\" data-selectable-paragraph=\"\">6. Check if an Element is Focused<\/h1>\n<p id=\"e4f4\" class=\"pw-post-body-paragraph kp kq jh kr b ks mr ku kv kw ms ky kz la mt lc ld le mu lg lh li mv lk ll lm ja fn\" data-selectable-paragraph=\"\">You can effortlessly check if an element is currently <strong class=\"kr ji\">focused<\/strong> without setting up the <code class=\"\" data-line=\"\">focus<\/code> &amp; <code class=\"\" data-line=\"\">blur<\/code> <strong class=\"kr ji\">listener<\/strong>.<\/p>\n<pre class=\"lp lq lr ls ha na fe nb\"><span id=\"1baf\" class=\"fn nc lu jh mz b do nd ne l nf\" data-selectable-paragraph=\"\">const hasFocus = (element) =&gt; element === document.activeElement;<\/span><\/pre>\n<h1 id=\"6a49\" class=\"lt lu jh bn lv lw lx ly lz ma mb mc md me mf mg mh mi mj mk ml mm mn mo mp mq fn\" data-selectable-paragraph=\"\">7. Count by the Properties of an Array of Objects<\/h1>\n<p id=\"944b\" class=\"pw-post-body-paragraph kp kq jh kr b ks mr ku kv kw ms ky kz la mt lc ld le mu lg lh li mv lk ll lm ja fn\" data-selectable-paragraph=\"\">Need to count the number of items in an <strong class=\"kr ji\">array<\/strong> that match a particular <code class=\"\" data-line=\"\">property<\/code>? Using <code class=\"\" data-line=\"\">reduce<\/code> on <strong class=\"kr ji\">arrays<\/strong> can achieve the task with ease!<\/p>\n<pre class=\"lp lq lr ls ha na fe nb\"><span id=\"4f3a\" class=\"fn nc lu jh mz b do nd ne l nf\" data-selectable-paragraph=\"\">const countElementsByProp = (arr, prop) =&gt;\n  arr.reduce(\n    (prev, curr) =&gt; ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev),\n    {}\n  );<\/span><span id=\"0acf\" class=\"fn nc lu jh mz b do nh ni nj nk nl ne l nf\" data-selectable-paragraph=\"\"><em class=\"ng\">\/\/ example<\/em>\ncountElementsByProp(\n  [\n    { manufacturer: \"audi\", model: \"q8\", year: \"2019\" },\n    { manufacturer: \"audi\", model: \"rs7\", year: \"2020\" },\n    { manufacturer: \"ford\", model: \"mustang\", year: \"2019\" },\n    { manufacturer: \"ford\", model: \"explorer\", year: \"2020\" },\n    { manufacturer: \"bmw\", model: \"x7\", year: \"2020\" },\n  ],\n  \"manufacturer\"\n); <em class=\"ng\">\/\/ { 'audi': 2, 'ford': 2, 'bmw': 1 }<\/em><\/span><\/pre>\n<p id=\"b920\" class=\"pw-post-body-paragraph kp kq jh kr b ks kt ku kv kw kx ky kz la lb lc ld le lf lg lh li lj lk ll lm ja fn\" data-selectable-paragraph=\"\"><strong class=\"kr ji\">NOTE:<\/strong> This too is a <strong class=\"kr ji\">one-liner<\/strong>, but spread across multiple lines for readability.<\/p>\n<p id=\"04b5\" class=\"pw-post-body-paragraph kp kq jh kr b ks kt ku kv kw kx ky kz la lb lc ld le lf lg lh li lj lk ll lm ja fn\" data-selectable-paragraph=\"\"><strong class=\"kr ji\">That\u2019s all folks!<\/strong><\/p>\n<\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p class=\"excerpt\">7 More Killer One-Liners in JavaScript | by Tapajyoti Bose | Apr, 2022 | Medium<\/p>\n<p class=\"more-link-p\"><a class=\"more-link\" href=\"https:\/\/monodes.com\/predaelli\/2022\/04\/28\/7-more-killer-one-liners-in-javascript-by-tapajyoti-bose-apr-2022-medium\/\">Read more &rarr;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"activitypub_content_warning":"","activitypub_content_visibility":"","activitypub_max_image_attachments":4,"activitypub_interaction_policy_quote":"anyone","activitypub_status":"","footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[50],"tags":[],"class_list":["post-9317","post","type-post","status-publish","format-standard","hentry","category-javascript"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6daft-2qh","jetpack-related-posts":[{"id":1614,"url":"https:\/\/monodes.com\/predaelli\/2016\/06\/01\/javascript-factory-functions-vs-constructor-functions-vs-classes-javascript-scene-medium\/","url_meta":{"origin":9317,"position":0},"title":"JavaScript Factory Functions vs Constructor Functions vs Classes \u2014 JavaScript Scene \u2014 Medium","author":"Paolo Redaelli","date":"2016-06-01","format":"link","excerpt":"https:\/\/medium.com\/javascript-scene\/javascript-factory-functions-vs-constructor-functions-vs-classes-2f22ceddf33e#.13avjf4lk","rel":"","context":"In &quot;Senza categoria&quot;","block_context":{"text":"Senza categoria","link":"https:\/\/monodes.com\/predaelli\/category\/senza-categoria\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":9080,"url":"https:\/\/monodes.com\/predaelli\/2022\/01\/23\/javascript-insanity\/","url_meta":{"origin":9317,"position":1},"title":"Javascript insanity?","author":"Paolo Redaelli","date":"2022-01-23","format":false,"excerpt":"On Facebook\u00a0they write I enjoy JavaScript but this is insanity Welcome to a language that has approximate math as the only math you can use. In fact 7110 \/ 100 * 100 is 7109.99999999 because the first division cannot be exactly represented with with a floating point representation. Sites like\u2026","rel":"","context":"In &quot;Fun&quot;","block_context":{"text":"Fun","link":"https:\/\/monodes.com\/predaelli\/category\/fun\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/monodes.com\/predaelli\/wp-content\/uploads\/sites\/4\/2022\/01\/javascript-insanity.webp?fit=520%2C372&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":9664,"url":"https:\/\/monodes.com\/predaelli\/2022\/09\/27\/15-weird-googling-tricks-99-9-of-developers-dont-know-about-javascript-in-plain-english\/","url_meta":{"origin":9317,"position":2},"title":"15 Weird Googling Tricks 99.9% of Developers Don&#8217;t Know\u00a0About | JavaScript in Plain English","author":"Paolo Redaelli","date":"2022-09-27","format":false,"excerpt":"15 Weird Googling Tricks 99.9% of Developers Don't Know\u00a0About | JavaScript in Plain English Well, I know most of them.","rel":"","context":"In &quot;Tricks&quot;","block_context":{"text":"Tricks","link":"https:\/\/monodes.com\/predaelli\/category\/documentations\/tricks\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":5130,"url":"https:\/\/monodes.com\/predaelli\/2019\/01\/15\/intuitive-asynchronous-javascript-edwin-yung-medium\/","url_meta":{"origin":9317,"position":3},"title":"Intuitive Asynchronous Javascript \u2013 Edwin Yung \u2013 Medium","author":"Paolo Redaelli","date":"2019-01-15","format":false,"excerpt":"Escape callback hell! Source: Intuitive Asynchronous Javascript \u2013 Edwin Yung \u2013 Medium \u00a0 Asynchronous Javascript Explained Simply and Intuitively Edwin Yung Dec 29, 2017 Escape callback hell with this\u00a0article! Asynchronous Javascript is difficult to wrangle. The following is my quick attempt to elucidate their inner workings. Before we get started,\u2026","rel":"","context":"In &quot;Documentations&quot;","block_context":{"text":"Documentations","link":"https:\/\/monodes.com\/predaelli\/category\/documentations\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":11779,"url":"https:\/\/monodes.com\/predaelli\/2024\/06\/29\/state-of-javascript-2023\/","url_meta":{"origin":9317,"position":4},"title":"State of JavaScript 2023","author":"Paolo Redaelli","date":"2024-06-29","format":false,"excerpt":"State of JavaScript 2023 The 2023 edition of the annual survey about the latest trends in the JavaScript ecosystem.","rel":"","context":"In &quot;Javascript&quot;","block_context":{"text":"Javascript","link":"https:\/\/monodes.com\/predaelli\/category\/javascript\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3228,"url":"https:\/\/monodes.com\/predaelli\/2017\/07\/20\/reverse-engineering-one-line-of-javascript\/","url_meta":{"origin":9317,"position":5},"title":"Reverse Engineering One Line of JavaScript","author":"Paolo Redaelli","date":"2017-07-20","format":false,"excerpt":"ASCII animations in 1 line of #JS. #JavaScript is really the assembler of the Web","rel":"","context":"In &quot;Javascript&quot;","block_context":{"text":"Javascript","link":"https:\/\/monodes.com\/predaelli\/category\/javascript\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts\/9317","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/comments?post=9317"}],"version-history":[{"count":0,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts\/9317\/revisions"}],"wp:attachment":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/media?parent=9317"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/categories?post=9317"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/tags?post=9317"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}