cft

Javascript snippets you need to know right now!

10 JS snippets of code every week to empower you to write better.


user

Abhiraj Bhowmick

2 years ago | 2 min read

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.

Let's 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

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"'

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');

5️⃣ 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'] ]

6️⃣ byteSize

This snippet returns the length of a string in bytes.

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

byteSize('😀'); // 4
byteSize('Hello World'); // 11

7️⃣ 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'

8️⃣ 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

9️⃣ 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'

🔟 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

Until next Wed,
Abhiraj

Upvote


user
Created by

Abhiraj Bhowmick

I make stuff on the web and write blogs about it.


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles