DEV Community

Cover image for 7 Killer One-Liners in JavaScript

7 Killer One-Liners in JavaScript

Tapajyoti Bose on February 13, 2022

7 Killer One-Liners in JavaScript JavaScript is the most crucial pillar of Web Development. This article contains code snippets hand-p...
Collapse
 
martinpham profile image
Martin Pham

1) It will lead to another problem: When navigator.clipboard is not available, the Promise.reject will be called, and probably you won't know: TypeError will be thrown (spec 25.4.4.4)
2) I'm not sure why using globalThis instead of window here btw

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€ • Edited

Point 2 is especially true

matchMedia will never be isomorphic, such recommendations appear to be blanket.

globalThis was not the original way to reference global and will still break some browsers unless a global.globalThis = global where global is window nor global, is referred to as a polyfill.

Thread Thread
 
martinpham profile image
Martin Pham

Correct!

 
adam_cyclones profile image
Adam Crockett πŸŒ€

I missed the point of globalThis?

No, I believe you have a firm grasp of JavaScript in general and understanding that globalThis brings safety through referencing whatever the global scope may be.

.. however, let's just step back, in this particular instance and many others, window is the only appropriate approach to access match media or any Browser based API, because;

  • there is no motivation from anyone including the community to add it to node.js or any other js environment
  • because it wouldn't do anything in any other environment

With such a low risk (which is the truth of programming, evaluation of risk to solve a problem as best you can)

Therefore as true optimization it's worth removing the complexity of polyfill, you are creating work for yourself in the name of safety

Example:
I am a banana but I could be an orange but the odds are extremely low that I am anything other than a banana, better prepare for both eventualities.

To me that's not efficient planning πŸ™‚

 
snigo profile image
Igor Snitkin

@lukeshiru your point about copyToClipboard is 100% legit, but maybe like this then:

const copyToClipboard = async (text) => navigator.clipboard.writeText(text);
Enter fullscreen mode Exit fullscreen mode

...so we're able to provide a rejection reason and not just throw text back

Thread Thread
 
martinpham profile image
Martin Pham

Yeah I knew you wouldn’t read the spec, that’s why I said you probably won’t know. Sadly.

 
adam_cyclones profile image
Adam Crockett πŸŒ€

Hey luke I think you miss the point, node will never use screen based APIs such as match media, therefore globalThis is never going to be needed. It's better to be precise about the usage of any code with reasoning which backs it up. There's no "maybe" in this case

 
Sloan, the sloth mascot
Comment deleted
Collapse
 
lexlohr profile image
Alex Lohr

There's an error in generateRandomColor: if math random is below 1/0x100000, the value may not have 6 characters.

// wrong:
const generateRandomHexColor = () =>
  `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;

// corrected:
const generateRandomHexColor = () =>
  `#${Math.floor(0x1000000 + Math.random() * 0xffffff).toString(16).slice(1)}`;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
snigo profile image
Igor Snitkin

Why not just padStart?

Collapse
 
lexlohr profile image
Alex Lohr

String.prototype.padStart is pretty recent and not supported by older browsers.

 
martinpham profile image
Martin Pham

1) Have you even read the spec I wrote?

2) lol

 
adam_cyclones profile image
Adam Crockett πŸŒ€ • Edited

The ultimate point here is that, you suggested something implicit globalThis is agnostic and implicit, window was correct and explicit, explicit tells me a little more about the intent of the code - in my head: "window suggests this must be browser only code"

My nitpicky points come from a good place. Do you know how much code runs behind the scenes for JavaScript to do a simple 2 plus 2? It's shockingly quite a lot! Although I won't let that put the fear into me, I don't believe in micro optimizations after all, I do believe that programming is exact, in the grand scheme from the computers perspective, it works or it don't. But the human, well that's a different story, humans make assumptions which lead to N number of understandings, so I feel that it's our job as programmers, writers of instructions, to layout out Intensions using explicit code, it is always clearer and carries some meta meaning, implicit is just magic it's implied with out reference and prior knowledge must be obtained.

I argue, and from several past mistakes I might add that adopting a blanket coding standard is pretty toxic, by adopting a rule for all cases without then thinking is this adding a little more work that should not happen in this situation, I believe that actually, this is the cause of most sub optimal code. Additionally globalThis is newish, it does nothing for a new programmer who may have seen thousands of bits of code with window

A wise programer once said:

"code must be smarter than table, but dumber than dog"

A sentiment that sticks with me almost 6 years after hearing it, to me, it means that simple (as in the intent) is not the same as simplyfied syntax and a fact I bitterly resent, by using the latest and greatest of any language features (typically abstractions) is then bringing a lot small pieces of overhead.

Lastly let's get quantitative, globalThis, how much have you used it and what percentage of it actually made it into both Node.js and Browser? Then answer this one, based on your previous answer, was it worth the saving? If the answer was, "not much but yes because it's easier." Does that mean perhaps you don't actually care about correct code. 😱

Thanks for playing, it's been fun πŸ›Œ

Collapse
 
andrewbridge profile image
Andrew Bridge

Sporadically in the same browser or varying across different browsers? I've certainly had to polyfill this behaviour option for Safari and several Chromium based browsers on macOS which is quite frustrating but never seen it fail to work when it is natively supported.

Collapse
 
vanekcheck profile image
Vanya • Edited

Actually, there is one problem with shuffle function

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);

// counts of appearances for all possible permutations
let count = {
  '123': 0,
  '132': 0,
  '213': 0,
  '231': 0,
  '321': 0,
  '312': 0
};

for (let i = 0; i < 1000000; i++) {
  let array = [1, 2, 3];
  shuffleArray(array);
  count[array.join('')]++;
}

for (let key in count) {
  console.log(`${key}: ${count[key]}`);
}
Enter fullscreen mode Exit fullscreen mode

// the result will be
"123: 374916"
"132: 62851"
"213: 125285"
"231: 62489"
"312: 62000"
"321: 312459"

We can see clearly: 123 and 321 appear much more often than others.

There are other good ways to do the task. For instance, there’s a great algorithm called Fisher-Yates shuffle. The idea is to walk the array in the reverse order and swap each element with a random one before it:

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
    [array[i], array[j]] = [array[j], array[i]];
  }
}
Enter fullscreen mode Exit fullscreen mode

source: javascript.info/array-methods#tasks

Collapse
 
jeydotc profile image
Jeysson Guevara

Well, It is hiding any error derived from the browser not supporting that API, and I wasn't referring to your solution in the comments (which looks cool), if that's what you think.

And no, I don't prefer to throw because of undefined, I prefer either your version of the solution (with the reject), or show a message to the user indicating the lack of support, or to directly hide the feature if we assert it beforehand.

Hiding an error is to catch/prevent an exception and do nothing with that, as the OP does, just think from an end user perspective, you'll click on a copy to clipboard button, then see a success message and then, when you attempt to paste... Nothing.

Collapse
 
jeydotc profile image
Jeysson Guevara

The copy to clipboard one is a really bad idea, in this case, you're just silencing a potential error without proper handling.

I've faced too many obscure bugs because of this kind of bad practice.

Collapse
 
gantlaborde profile image
Gant ℒ𝒢𝒷ℴ𝓇𝒹ℯ

It makes me so sad that JavaScript still needs these functions explained instead of part of the standard lib in 2022.

Collapse
 
igormelo profile image
Igor Melo

You can use optional chaining for functions too, so:

navigator.clipboard?.writeText?.(text);
Enter fullscreen mode Exit fullscreen mode

Is valid

Collapse
 
dayliver profile image
dayliver

Beautiful!

Collapse
 
andrewbaisden profile image
Andrew Baisden

Dope some good ones in here.

Collapse
 
bacloud22 profile image
aben • Edited

we need more and more like dozens !!! Better to specify running on which platform: browsers and nodejs