DEV Community

Cover image for Have a Handy JS Snippet You Want to Share?

Have a Handy JS Snippet You Want to Share?

Nick Taylor on January 23, 2018

So it's pretty simple. I'm looking for one or two lines of JavaScript that do something useful. I'll get the ball rolling and start with some exam...
Collapse
 
prodigalknight profile image
RevanProdigalKnight • Edited

Another one I just remembered:

// Automatically escapes all backslashes in the RegExp when stringifying
const stringWithEscapedBackslashes = /\\\\\\this \\\string has lots\ of \\\\backslashes for \\ some reason./.source;
// yields "\\\\\\\\\\\\this \\\\\\string has lots\\ of \\\\\\\\backslashes for \\\\ some reason."
Collapse
 
nickytonline profile image
Nick Taylor

It looks like the escaping only works in FireFox according to the MDN docs, RegExp.prototype.source (see Browser Compatibilty section).

Collapse
 
prodigalknight profile image
RevanProdigalKnight • Edited

Hmm. I verified that the MDN isn't just out of date by testing in Chrome. I can't remember the context I was using that snippet in precisely, but I do remember it was designed to run in IE10+, Chrome, and Firefox.

I may have just been using it so I wouldn't have to escape all my backslashes for a string.

Thread Thread
 
nickytonline profile image
Nick Taylor

I tried in Chrome yesterday and it doesn't error out, but it just doesn't escape.

Collapse
 
blouzada profile image
Bruno Louzada

Wow

Collapse
 
aravindballa profile image
Aravind Balla • Edited

An amazing line from @wesbos podcast syntaxfm

await (await fetch('https://api.github.com/users/wesbos')).json();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
juliani profile image
Julian Iaquinandi

I've not had a chance to listen to the episode yet. Any Chance you can explain this one? Thought I had started to understand async/ await until I saw this! Thanks.

Collapse
 
aravindballa profile image
Aravind Balla • Edited

Let me break that up.

const response = await fetch('https://api.github.com/users/wesbos');

const data = await response.json(); //this gives us the JSON data from the response.
Enter fullscreen mode Exit fullscreen mode

Previously it used to be,

fetch('https://api.github.com/users/wesbos')
.then(res => res.json()) //json() also returns a promise
.then(data => {console.log(data)});

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
juliani profile image
Julian Iaquinandi

Ahhh I see, that's amazing thanks for that! <3

Thread Thread
 
wesbos profile image
Wes Bos

Thanks! I just clarified this in a tweet:

twitter.com/wesbos/status/95583181...

Thread Thread
 
juliani profile image
Julian Iaquinandi

Thanks Wes, keep up the good work! Loving them tasty treats :P

Collapse
 
aarohmankad profile image
Aaroh Mankad • Edited

Here's a super easy way to remove duplicates from an array (by using the definition of a Set)!


const unique = (arr) => [...new Set(arr)]

// [1, 2, 3, 4, 5]
console.log(unique([1, 1, 2, 3, 4, 5, 5]))

Collapse
 
nickytonline profile image
Nick Taylor

Yup that's a good one, although I already have it up top 😺 .

Collapse
 
aarohmankad profile image
Aaroh Mankad

Oh haha, didn't see that one!

Collapse
 
mschleeweiss profile image
Marc Schleeweiß

You have an array with keys and one with values and want to merge them into an object?

keys = ["a", "b", "c"]
values = [1, 2, 3]

keys.reduce((obj, k, i) => ({...obj, [k]: values[i] }), {})
// result is {a: 1, b: 2, c: 3}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
prodigalknight profile image
RevanProdigalKnight • Edited

Quick-and-easy deferred promise (like from q.defer()) - handy for modal dialogs:

class Deferred {
  constructor() {
    this.promise = new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;
    });
  }
}

// example
function dialog() {
  const deferred = new Deferred();

  // create dialog here
  ...

  // Finally, set up the button click handlers
  dialog.okButton.onclick = deferred.resolve;
  dialog.cancelButton.onclick = deferred.reject;

  return deferred.promise;
}

// Alternatively
function dialog() {
  const { promise, resolve, reject } = new Deferred();

  // etc...

  dialog.okButton.onclick = resolve;
  dialog.cancelButton.onclick = reject;

  return promise;
}

dialog().then(/* success! */, /* cancelled */);

Better than wrapping all of that code inside of a Promise constructor every time, in my opinion.

Collapse
 
jarpi profile image
Josep • Edited

Quick unhasher (not a generic one, but it does the job)



const seed = 7
const prime = 37
const letters = "acdegilmnoprstuw"

const unhash = (hash, acc, letterOffset = 0) => {
  if (hash === seed) return acc
  for (;hash%prime>0;hash--,letterOffset++);
  return unhash(hash/prime, letters[letterOffset] + acc)
}