DEV Community

Cover image for Javascript snippets you need to know right now 🔥 - #1
Abhiraj Bhowmick
Abhiraj Bhowmick

Posted on • Updated on • Originally published at abhiraj.mdx.one

Javascript snippets you need to know right now 🔥 - #1

JavaScript is one of the most popular languages you can learn. As many people say: “If you’re going to learn just one programming language, go for JavaScript.”

If this sounds compelling to you, I am starting a series where i give 10 Javascript snippets every Wednesday for 5 weeks.
This tweet of mine had originally inspired me to create this series, do drop a like and follow me.

Here’s a list of 10 beneficial snippets that you can learn and use immediately.

Lets get started!

1️⃣ all

This snippet returns true if the predicate function returns true for all elements in a collection and false otherwise. You can omit the second argument 'fn' if you want to use Boolean as a default value.

const all = (arr, fn = Boolean) => arr.every(fn);

all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true
Enter fullscreen mode Exit fullscreen mode

2️⃣ arrayToCSV

This snippet converts the elements to strings with comma-separated values.

const arrayToCSV = (arr, delimiter = ',') =>
  arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');

arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
Enter fullscreen mode Exit fullscreen mode

3️⃣ arrayToHtmlList

This snippet converts the elements of an array into list tags and appends them to the list of the given ID.

const arrayToHtmlList = (arr, listID) =>
  (el => (
    (el = document.querySelector('#' + listID)),
    (el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))
  ))();

arrayToHtmlList(['item 1', 'item 2'], 'myListID');
Enter fullscreen mode Exit fullscreen mode

4️⃣ bifurcate

This snippet splits values into two groups and then puts a truthy element of filter in the first group, and in the second group otherwise.

You can use Array.prototype.reduce()and Array.prototype.push()to add elements to groups based on filter.

const bifurcate = (arr, filter) =>
  arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); 
// [ ['beep', 'boop', 'bar'], ['foo'] ]
Enter fullscreen mode Exit fullscreen mode

5️⃣ byteSize

This snippet returns the length of a string in bytes.

const byteSize = str => new Blob([str]).size;

byteSize('😀'); // 4
byteSize('Hello World'); // 11
Enter fullscreen mode Exit fullscreen mode

6️⃣ capitalize

This snippet capitalizes the first letter of a string.

const capitalize = ([first, ...rest]) =>
  first.toUpperCase() + rest.join('');

capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar'
Enter fullscreen mode Exit fullscreen mode

7️⃣ dayOfYear

This snippet gets the day of the year from a Dateobject.

const dayOfYear = date =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date()); // 272
Enter fullscreen mode Exit fullscreen mode

8️⃣ decapitalize

This snippet turns the first letter of a string into lowercase.

const decapitalize = ([first, ...rest]) =>
  first.toLowerCase() + rest.join('')

decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar'); // 'fooBar'
Enter fullscreen mode Exit fullscreen mode

9️⃣ countOccurrences

This snippet counts the occurrences of a value in an array.

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
Enter fullscreen mode Exit fullscreen mode

🔟 default
This snippet assigns default values for all properties in an object that are undefined.

const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);

defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }
Enter fullscreen mode Exit fullscreen mode

Until next Wed,
Abhiraj

Top comments (1)

Collapse
 
abhirajb profile image
Abhiraj Bhowmick

Thanks a lot for adding on!