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.
Abhiraj Bhowmick@rainboestrykr
5 Javascript snippets for you to write better code 🔥🔥🔥 (Part 1)
A thread🧵👇
#webdevelopment #webdev #javascript #techtwitter #devcommunity07:45 AM - 04 Nov 2021
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
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');
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'] ]
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
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'
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
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'
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
🔟 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 }
Until next Wed,
Abhiraj
Top comments (2)
A few things:
all
is not that valuable compared to just usingArray.prototype.every
, so you could just make it a currie function instead:arrayToCSV
might break if a value in the array has the"
on it, because is not being scaped.arrayToHtmlList
can be improved a little. Instead of usingid
, you just receive the actual element (so the dev can use any selection they want instead of having to have anid
), and you usetextContent
so you aren't accidentally setting broken html. It could be improved further so that the mapping to HTML elements happens in other function, that let's you map to other things besidesli
, but I'll let you figure that out:bifurcate
could be simplified a little by omittingreduce
:capitalize
could be implemented without turning it into an array, and covering possible undefined values. You can do the same fordecapitalize
:countOccurrences
could just usefilter
instead ofreduce
:Cheers!
Thanks a lot for adding on!