DEV Community

Cover image for JavaScript One-Liners That Make Me Excited

JavaScript One-Liners That Make Me Excited

Andrew Healey on March 28, 2019

Dust off your ternary expressions, we're going in. One-liners are tricky to maintain (and sometimes even hard to understand) but that doesn't stop...
Collapse
 
michi profile image
Michael Z

I've got another good one to create arrays of a specific size and map over it at the same time.

Array.from({length: 3}, (val, i) => i)
// [0, 1, 2]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dhe profile image
d-h-e
[...Array(3).keys()]
// [0, 1, 2]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
qm3ster profile image
Mihail Malo

Oh SHID.
This is exactly what I needed so many times, and it finally seems like it's a performant approach?!

Collapse
 
brian profile image
Brian • Edited

It looks quite clean and sleek, so I decided to test out the performance on my pc

Weirdly using Array(N) is about 20% faster than using an array-like {length: N} when used inside Array.from()

I also added comparisons of mapping as a parameter vs (dot)map too.

Thread Thread
 
qm3ster profile image
Mihail Malo

Wow, that's... humbling.
BTW, you could beat out ForLoop with:

const arr = new Array(100)
for (let i = 0, i < 100, i++)
  arr[i] = i

since the size is known in advance.

Collapse
 
lexlohr profile image
Alex Lohr

You can shave off one more char for your hex color code generator without resorting to padEnd:

// before
'#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0');

// after
'#' + (0x1000000 + Math.random() * 0xffffff).toString(16).slice(1, 6);
Collapse
 
healeycodes profile image
Andrew Healey

A clever change. Probably faster too?

Collapse
 
lexlohr profile image
Alex Lohr

Thanks. Not sure if it's faster, but that's usually a non-issue for code golfing :)

Collapse
 
rithvikvibhu profile image
Rithvik Vibhu

I was curious and created a test: jsperf.com/hex-color-code-generator
:)

Thread Thread
 
healeycodes profile image
Andrew Healey

Awesome! Close to what I expected 👍

Collapse
 
moopet profile image
Ben Sinclair • Edited
// I'd like to see a minifier work that hard.
document.location.search.replace(/(^\?)/,'').split('&').reduce(function(o,n){n=n.split('=');o[n[0]]=n[1];return o},{});

// Challenge accepted.
location.search.substr(1).split('&').reduce((o,n)=>{n=n.split('=');o[n[0]]=n[1];return o},{});
Enter fullscreen mode Exit fullscreen mode

I'm not a big Javascript person so I don't know what the difference is between window.location, document.location and just location (which I assume uses the global window context). I know substr works fine on an empty string, and I'm making the (heroically cavalier) assumption that query strings start with a ? in all browsers' implementations of location.search.

But both of these return something incorrect if there's no query string:

{"": undefined}
Enter fullscreen mode Exit fullscreen mode

Oops. Well, we can do something about that:

(() => {let x=location.search.substr(1).split('&').reduce((o,n)=>{n=n.split('=');o[n[0]]=n[1];return o},{});delete x[""];return x})()
Enter fullscreen mode Exit fullscreen mode

And now it's longer and even less maintainable, but hey :)

Collapse
 
healeycodes profile image
Andrew Healey

This is brilliant, Ben! 😄

Collapse
 
lexlohr profile image
Alex Lohr

I can probably do it in even less characters... let me try:

q={};document.location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;
Thread Thread
 
luckybilly profile image
齐翊

Hey, that one could not accept empty value (eg:'?a=&b=1&c=')
try this instead:

//keys should not be empty, but value can
q={};location.search.replace(/([^?&=]+)=([^&]*)/g,(_,k,v)=>q[k]=v);q;
Collapse
 
sabberworm profile image
Raphael Schweikert • Edited

Be careful with that shuffle, it won’t yield truly random results because sort expects its comparator to uphold Math.sign(compare(a, b)) === -Math.sign(compare(b, a)). Microsoft once screwed up by using exactly that.

Collapse
 
healeycodes profile image
Andrew Healey

What an interesting story! Thanks for sharing.

And yes, for any production code just use Fisher/Yates!

Collapse
 
chiangs profile image
Stephen Chiang

Awesome one liners... Until you hit save and Prettier formats it to two 🤣

Collapse
 
elmuerte profile image
Michiel Hendriks • Edited

Why waste all those extra characters, this also works

(arr) => arr.slice().sort(() => Math.random() - 0.5)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
healeycodes profile image
Andrew Healey

Nice find, thanks! Edited 👍.

Collapse
 
brianjenkins94 profile image
Brian Jenkins • Edited

Does this count? 😈

{
    "precommit": "git ls-files | while read -r FILE; do if file \"$FILE\" | grep -q \"text\"; then vim --clean -n -e -s -c \":%s/\\s\\+$//e|:retab|:wq\" \"$FILE\"; fi ; done"
}
Collapse
 
healeycodes profile image
Andrew Healey

I'll allow it! 😀

Collapse
 
greg profile image
greg

It's a shorthand for returning one of three colors if the score is truthy. Otherwise it returns a fallback value.

score => ({1: "#98FB98", 2: "#FFFF99", 3: "#FA8072"}[score] || "#DCDCDC")
Collapse
 
lexlohr profile image
Alex Lohr

that can be even more minified:

score => (["", "#98FB98", "#FFFF99", "#FA8072"][score] || "#DCDCDC")

you could lose the first array item and use score - 1, but that would have more characters.

Collapse
 
kenbellows profile image
Ken Bellows

Would it? Wouldn't you shorten by 4 chars to remove "",, or 3 if whitespace doesn't count, and only add 2 chars to go from [score] to [score-1]? Seems like it'd still be shorter by at least a character, or am I missing something?

Collapse
 
daksamit profile image
Dominik Aksamit

The one I recently discovered as very useful, mostly while testing or mocking API calls:

await new Promise((resolve) => setTimeout(() => resolve(1), 2500));
Enter fullscreen mode Exit fullscreen mode

Usually I use, when I have to simulate data fetching ;P

Collapse
 
healeycodes profile image
Andrew Healey

Very cool! Thanks for sharing Dominik 👍

Collapse
 
daksamit profile image
Dominik Aksamit

Thanks! I would recommend adding most of them to vscode snippets. It's really easy to use just like typing "sleep" + enter and I have ready one-liner in my code ;)

Collapse
 
lexlohr profile image
Alex Lohr

There are a lot of byte saving tips one can employ in code golfing. A nice collection can be found here: github.com/jed/140bytes/wiki/Byte-...

Collapse
 
jacobmgevans profile image
Jacob Evans • Edited
isInRange = (a, b, c) => [...Array(c - a +1)].map((e, i) => i + a).indexOf(b) !== -1

I did this one for a challenge. It finds if a number is in a range of two other numbers so find if b is in range of a to c

Collapse
 
nestedsoftware profile image
Nested Software • Edited

Wouldn't you just check b >= a && b <= c ?

Collapse
 
jacobmgevans profile image
Jacob Evans

That was definitely a way to do it. However, I am pretty sure that only works with constraints on the range values, and the way I wanted to solve it was to be sure it could handle any range.

I could be wrong which in that case, I will certainly remember this way lol

Thread Thread
 
jacobmgevans profile image
Jacob Evans

Nope to me lol, you're just right and I am pretty sure that works for any size range not just that but the
Big O is significantly better ahahaha!

Collapse
 
korbraan profile image
Cédric Rémond

I use Set often to remove duplicates, but I didn't know it's possible to use the spread operator on a Set.

I have been using Array.from(new Set(myArray)) until now. Since Array.from take an iterable I could have guessed but...

Nice post !

Collapse
 
healeycodes profile image
Andrew Healey

Glad it helped ya!

Collapse
 
kelerchian profile image
Alan
const makeMockingSpongebobMeme = (someString) => (typeof someString === "string" ? someString : "Wrong input").split("").map(a => Math.random() > 0.5 ? a.toLowerCase() : a.toUpperCase()).join("")

One of the intriguing trait of functional programming is to look unreadable despite being working.

Collapse
 
luckybilly profile image
齐翊 • Edited
q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;

got a problem like this:

'?a=&b=1&c='  ----> {b: 1} 

lost key 'a' and 'c'

solution: replace the 2nd '+' by '*'

q={};location.search.replace(/([^?&=]+)=([^&]*)/g,(_,k,v)=>q[k]=v);q;
Collapse
 
healeycodes profile image
Andrew Healey • Edited

Thanks! Fixed it :)

Collapse
 
sebastienbarre profile image
Sebastien Barre

Please don't use code in production that multiplies 86400000 (24*60*60*1000) for computing dates; date/time is way more complicated than that, you will shoot yourself in the foot. Use a library.

Collapse
 
qm3ster profile image
Mihail Malo • Edited
const r = {valueOf: Math.random}

Not really a one-liner, but good for when making generative art.

Collapse
 
caseycole589 profile image
Casey Cole • Edited

//only rounds up 15 can be changed to what ever number you want to use
roundMinutes = (mins) => { return (~(mins / 15) * 15) * -1 ; }
roundMinutes(35) -> 45
// will now round down instead of up
roundMinutes = (mins) => { return (~~(mins / 5) * 5) ; }

Collapse
 
kioviensis profile image
Max Tarsis

great stuff
thanks

Collapse
 
flexdinesh profile image
Dinesh Pandiyan

A keyboard so real you can taste it

Love it!

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
morenomdz profile image
MorenoMdz

Good stuff thanks!!

Collapse
 
fluffy profile image
fluffy

Note that list shuffle approach has a bunch of bias and doesn't perform very good shuffling. See beesbuzz.biz/code/6719-How-not-to-... for a detailed explanation.

Collapse
 
healeycodes profile image
Andrew Healey

Yup! 😀 The function is short but scary. Raphael linked another article that covers the same topic. I'll add a note.

Collapse
 
kimsean profile image
thedevkim

google search got me here. Thank you for this article. This one's i've been looking for.

Collapse
 
moopet profile image
Ben Sinclair

A couple of comments!

Anything that has semicolons in it isn't a one-liner, no matter how you try to stretch the definition.

And does it matter that days aren't always 86400000 milliseconds long?

Collapse
 
wayne_gakuo profile image
Wayne Gakuo

This article makes JavaScript look really fun to play with. Thanks Andrew!

Collapse
 
healeycodes profile image
Andrew Healey

Yeah, this one was fun to write! 😁

Collapse
 
codercatdev profile image
Alex Patterson

Now I need the bash (or if Apple forces me zsh) script so I can call the command sevenDays ;)

Collapse
 
healeycodes profile image
Andrew Healey

I like it a lot.