Three Simple Algorithms with JavaScript
You might have seen some of these algorithm challenges before, but that’s okay, we’re offering a few solutions to each of them, to help give you a better understanding of them and enhance your problem-solving abilities for other algorithms you might come across in the future.
Reverse a String
Reversing a string is perhaps one of the first algorithmic challenges you will see. It is pretty easy to solve it, especially in JavaScript.
Directions
Given a string, return a new string with the reversed order of characters
Examples
reverse('apple') === 'leppa'
reverse('hello') === 'olleh'
reverse('Greetings!') === '!sgniteerG'
Solution(s):
The quick and easy way:
function reverse(str) {
return str.split("").reverse().join("");
}
console.log(reverse("apple"));
// Outut: 'leppa';
Using .reduce()
:
function reverse(str) {
return str.split("").reduce((rev, char) => char + rev, "");
}
console.log(reverse("apple"));
// Outut: 'leppa';
Using a for of
loop:
function reverse(str) {
let reversed = "";
for (let character of str) {
reversed = character + reversed;
}
return reversed;
}
console.log(reverse("apple"));
// Outut: 'leppa';
Reverse an Int
Reversing an int is much like reversing a string, only that there’s a small change you must keep in mind - changing the data type of the returned value to be a Number.
Directions
Given an integer, return an integer that is the reverse ordering of numbers.
Examples
reverseInt(15) === 51
reverseInt(981) === 189
reverseInt(500) === 5
reverseInt(-15) === -51
reverseInt(-90) === -9
Solution(s):
Using parseInt()
:
function reverseInt(n) {
const reversed = n.toString().split("").reverse().join("");
return parseInt(reversed) * Math.sign(n);
}
console.log(reverseInt(15));
// Output: 51
We only offer one solution for this because it’s so similar to the previous challenge.
Capitalize a String
Now that we’ve got two reversals out of the way, we’ll explore another fun challenge – Capitalizing a string.
Directions
Write a function that accepts a string. The function should capitalize the first letter of each word in the string then return the capitalized string.
Examples
capitalize('hello, there!') --> 'Hello, There!'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'
Solution(s):
With a for
loop:
function capitalize(str) {
let result = str[0].toUpperCase();
for (let i = 1; i < str.length; i++) {
if (str[i - 1] === " ") {
result += str[i].toUpperCase();
} else {
result += str[i];
}
}
return result;
}
console.log(capitalize("hello, there!"));
// Output: 'Hello, There!'
With a for of
loop:
function capitalize(str) {
const words = [];
for (let word of str.split(" ")) {
words.push(word[0].toUpperCase() + word.slice(1));
}
return words.join(" ");
}
console.log(capitalize("hello, there!"));
// Output: 'Hello, There!'
That’s it!
There we have it, three simple algorithms solved with JavaScript. Stick around, there will be many more articles like this. Let us know what you think in the Disqus comments below. Would you like us to write about a particular algorithm or data structure?
Related Posts
The Art of Data Visualization: Exploring D3.js
Data is everywhere, flowing into our applications from various sources at an unprecedented rate. However, raw data alone holds little value unless it can be transformed into meaningful insights.
Read moreJavaScript’s Secret Weapon: Supercharge Your Web Apps with Web Workers
During an interview, I was asked how we could make JavaScript multi-threaded. I was stumped, and admitted I didn’t know… JavaScript is a single-threaded language.
Read moreCreating a NodeJS Budgeting Tool
In this article, we’re going to show you how to read and write to a .txt file using NodeJS by creating a small budgeting CLI (Command Line Interface).
Read more