9 Neat JavaScript Snippets For Algorithms And More
Tags: javascript, codenewbie, webdev, algorithms
Published: 2021-07-12 17:52:20

Knowing certain JavaScript one liners can save you valuable time while developing or interviewing. Here are some of my favorite “once you know, you know” snippets that I have actually used while coding. Only one of them is a bit code golf-y, and unsurprisingly it uses reduce.

## Wrap around a list

Spinning is a neat trick, but so is wrapping. A lot of times in algorithms you will need to wrap around a list. Meaning move a number of spaces, and if you reach the end of the list, go back to the first index. So if a list is 8 values long, but you have to move 10, you would need to land on the second index. You could use a bunch of complicated if statements, OR…

```js 
const wrap = (arr, steps) => arr[steps % arr.length];
wrap(['a','b','c'], 0) // a 
wrap(['a','b','c'], 1) // b
wrap(['a','b','c'], 2) // c
wrap(['a','b','c'], 3) // a 
// etc ...
```

You can implement this differently based off steps, but the key thing to understand is [the modulo](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder). It’s a handy little operator, keep it in mind when looking at “overflow” type problems like this.

## Log a variable with its name

This is such a great trick when debugging. Thanks to [object shorthand notation](https://alligator.io/js/object-property-shorthand-es6/) we can log out variables with names by default.

```js
const someVar = 1;
console.log({ someVar });
// logs out { someVar: 1 }
```

If you put in a bunch of logs (and you totally will when debugging), it can be hard to keep track of which is which with all the asyncs, fetches, and loops flying around. Instead of having to take the time to type multiple args like `console.log('some var', someVar)`, toss in some curly brackets and call it a day.

## Optional properties in objects

If you don’t want properties pointing to undefined or null , you might use some if statements to optionally add properties:

```js
//...
const obj = {
  a: 'whatever',
};
if (b) {
  obj.c = 'ok';
}
return obj;
//...
```

However, it’s verbose and I’ve always hated it. It may be clear, but it’s clunky. Well, thanks to object spreading, it’s a thing of the past:

```js
return {
  a: 'Whatever',
  ...(b && { c: 'ok'}),
};
```

We can use a [spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [&& logical short circuiting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#short-circuit_evaluation) to dynamically check whether or not to add the property by spreading it. This comes most in handy when you just want to return an object, and don’t want to create a temporary variable.

## Sleep in JavaScript

A few times I had to deal with a terrible API that was slow and didn’t have a hook to say when it finished. So, we just had to wait a second to make sure it loaded. We also wanted to use promises instead of setTimeout callbacks, so using a sleep function was ideal. We could simply await for a second and then move on. No need for callbacks!

```js
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
```

Here’s how to [promisify setInterval](https://levelup.gitconnected.com/how-to-turn-settimeout-and-setinterval-into-promises-6a4977f0ace3?sk=80ad1ba261951e1a6cb422db1e51e6c0) as well.

## Swap variable values

Before modern JS, if you wanted to switch the values of two variables, you’d have to introduce a 3rd ‘temp’ value. Now that we have [array destructuring and assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), we can do it in one line:

```js 
a = 10;
b = 5;
[a,b] = [b,a];
// a is 5, b is 10
```

## Round to nearest 10, 100, 1000…

This one is useful in algorithms if you need to rough out numbers to various levels. Basically, what you’re doing is dividing first to move the decimal up. With the “useless” numbers now decimals, you can round them off. To get the number back up to its desired size, you multiply it. The ignored numbers now become zeros. It’s a neat trick for dealing with money or logarithm-like scales where after a certain point, small numbers can be rounded off.

```js
const rounder = (val, place) => Math.round(val / place) * place;
rounder(1549, 100); // 1500
rounder(15590, 1000); // 16000
```

## Remove duplicates with Set

I just wrote about [Sets](https://medium.com/geekculture/should-you-use-javascript-maps-and-sets-1660647b55da?sk=e558f84be27e19e91426e03750fd56ef), and apparently this is kind of their only use. If you have an array and you want to remove the duplicates, you can do so with a Set.

```js
const val = [...new Set([1,2,1,3,1,4])];
// [ 1, 2, 3, 4 ]
```

Don’t forget to spread the new Set back into a regular array. Note: be careful with massive lists, as this may not be the most performant solution.

## Count character instances

If you have an array (or array from a string) and want to know how many times characters appear, there’s a super slick way to do this with reduce.

```js
const charTotals = (arr) => arr.reduce((totals, char) => ({ 
  ...totals, [char]: (totals[char] || 0) + 1, 
}), {});
charTotals('Hi there!'.split(''));
// { H: 1, i: 1, ' ': 1, t: 1, h: 1, e: 2, r: 1, '!': 1 }
```

This one might not be all that useful, but there are 2 techniques that I want to make sure you know: [dynamic object properties](https://www.samanthaming.com/tidbits/37-dynamic-property-name-with-es6/) and implicit [returns with an object](https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript). Both of those things are crucial knowledge, and if you don’t [understand reduce, then read this](https://levelup.gitconnected.com/javascript-has-a-reduce-method-you-should-use-it-ff4dd29d6c9d?sk=da559dd1a04170eb124f10e2f43cebae).

## ID maker/counter

I think I needed to dynamically create non-db temp ids for react components and squished a [classic counter](https://www.w3schools.com/js/js_function_closures.asp) into one line. Each time the function is called, the counter increases, and no other function can alter its internal state. It uses a [closure](https://itnext.io/a-beginners-guide-to-understanding-javascript-closures-b5eb57fdbeb4?sk=921273adc0bc6e1f2d9dd87310913401), [Immediately Invoked Function Expression](https://developer.mozilla.org/en-US/docs/Glossary/IIFE), and a default value to keep things tight.

```js
const counter = ((num = 1) => () => num++)();
counter() // 1
counter() // 2
counter() // 3
```

Also bonus tip to use default values in function parameters to avoid needing a new line. And you can stop making it an IIFE if you actually want to make the starting number dynamic:

```js
const startCounter = (num = 1) => () => num++);
const counter100 = startCounter(100)
counter100() // 100
counter100() // 101
counter100() // 102
```

## A word on readability

Look, I’m all about [readable code](https://itnext.io/tips-for-writing-self-documenting-code-e54a15e9de2?sk=02d1d7a2f1bb798dc0227cb56485e98b) and I’ll be the first person to say that some of these snippets aren’t super straightforward. What you get in brevity you lose in readability. Now, personally, I don’t think any of these are too wild, but others might disagree. That’s why you should try to use small, named functions and descriptive variables. These pieces can be the crucial tip to help your code click for others. But, ultimately it comes down to what you and your team like, so feel free to modify or expand anything here. And if you have any clever one liners you love, please show them off in the comments!

happy coding everyone,

mike