JavaScript Exercises from 1 to 15

parent d989ba00
//JavaScript Exercises:
// “Hello, World!” printed
console.log('Hello, World!')
// 1. Reverse
function reverse(string) {
let splitString = string.split(''); // to split the string letters into an array
let reverseLetters = splitString.reverse(); // to reverse the inicial array and save it in a variable
let joinString = reverseLetters.join(''); // to join the string back together
return joinString;
};
console.log(reverse('Please!')); // !esaelP
// 2. Factorial
function factorial(n) {
if (n < 0) {
return 'n must be > or = to 0'; // for negative number
}
else if (n == 0) {
return 1; // for zero
}
else {
return (n * factorial(n - 1)); // for positive numbers
}
};
console.log(factorial(-6)); // n must be > or = to 0
console.log(factorial(0)); // 1
console.log(factorial(3)); // 6
// 3. Longest Word
function longest_word(sentence) {
const words = sentence.split(' ');
let longest = '';
for (i = 0; i < words.length; i++) {
if (longest.length < words[i].length) { // compare strings and save on 'longest' the longest one
longest = words[i];
}
}
return longest;
};
console.log (longest_word('The longest word works')); // longest
// 4. Sum Nums
function sum_nums(num) {
let sum = num; // inicialize sum
let n = num; // inicialize n
for (i = 0; i < num; i++) {
sum = sum + (n-1); // sum of previous numbers plus n-1
n = (n -1); // saving n-1 on n for the new cicle
}
return sum;
};
console.log(sum_nums(5)); // 15
// 5. Time Conversion
function time_conversion(minutes) {
if (minutes >= 0) {
let hours = Math.floor(minutes/60); // separate hours from minutes after division for 60
let lastminutes = minutes - hours*60; // give the leftover minutes
if (hours < 10) {
hours = `0${hours}`; // to put in the format 00:00
};
if (lastminutes < 10) {
lastminutes = `0${lastminutes}`; // to put in the format 00:00
};
return `${hours}:${lastminutes}`;
}
};
console.log(time_conversion(130)); // 02:10
console.log(time_conversion(122)); // 02:02
console.log(time_conversion(650)); // 10:50
// 6. Count Vowels
function count_vowels(string) {
str = string.toLowerCase();
let letters = str.split(''); // to split the string letters into an array
let count = 0; // inicialize a counter of vowels
for (i = 0; i < letters.length; i++) {
if (letters[i] == 'a' || letters[i] == 'e' || letters[i] == 'i' || letters[i] == 'o' || letters[i] == 'u') {
count = count + 1; // if a vowel is found, counter receive +1
}
}
return count;
};
console.log(count_vowels('HelloWorld')); // 3
console.log(count_vowels("I'm home!")); // 3
console.log(count_vowels('H A P P Y')); // 1
// 7. Palindrome
function palindrome(string) {
str = string.toLowerCase();
const splitString = str.split(''); // to split the string letters into an array
const reverseLetters = splitString.reverse(); // to reverse the inicial array and save it in a variable
const joinString = reverseLetters.join(''); // to join the string back together
return str == joinString;
};
console.log(palindrome('day')); // false
console.log(palindrome('Ana')); // true
// 8. Most Letters
function nearby_az(string) {
str = string.toLowerCase();
const splitString = str.split(''); // to split the string letters into an array
for (i = 0; i < splitString.length; i++) {
return (splitString[i] == 'a' && (splitString[i+1] == 'z' || splitString[i+2] == 'z' || splitString[i+3] == 'z'))
}; // return (true) if a letter “z” appears within three letters after an “a”
};
console.log(nearby_az('az')); //true
console.log(nearby_az('arrrrz')); // false
console.log(nearby_az('allez')); // false
console.log(nearby_az('arrz')); // true
// 9. Two Sum
function two_sum(nums) {
let positions = [];
for (i = 0; i < nums.length; i++) {
for (j = i+1; j < nums.length; j++) {
if (nums[i] + nums[j] === 0) {
positions.push(i,j);
};
};
};
if (positions.length == 0) {
return null;
}
else {
return positions;
}
};
console.log(two_sum([1, 3, -1, 5])); // [[0, 2])
console.log(two_sum([1, 3, -1, 5, -3])); // [[0, 2], [1, 4]]
console.log(two_sum([1, 5, 3, -4])); // null
// 10. Is Power of Two
function is_power_of_two(num) { // didn't considered negative numbers for exponent (ex: 2⁻² or 2⁻⁵)
if (num <= 0) {return false}; // impossible
while ((num%2) == 0) { // while the rest of the division is 0 keep dividing
num = num/2;
}
return num == 1; // if the final number after the divisions is 1 return true (it's a power of 2)
};
console.log(is_power_of_two(16)); // true
console.log(is_power_of_two(6)); // false
console.log(is_power_of_two(8)); // true
console.log(is_power_of_two(0)); // false
// 11. Repeat a string
function repeat_string_num_times(str, num) {
if (num > 0) { // return an empty string if num is not a positive number
const string = str.repeat([num]);
return string;
}
else {
return '';
}
};
console.log(repeat_string_num_times('123', 0)); // ''
console.log(repeat_string_num_times('abc', 2)); // abcabc
console.log(repeat_string_num_times('abc', -2)); // ''
console.log(repeat_string_num_times('ho', 4)); // hohohoho
// 12. Sum All Numbers in a Range
function add_all(arr) { // assumed that will only be passed arrays with 2 numbers
let firstnumber = arr[0];
const secondnumber = arr[1];
let sum = 0;
while (firstnumber <= secondnumber) { // while the first number is <= then the second number, add it to the sum
sum = sum + firstnumber;
firstnumber = firstnumber + 1;
};
return sum;
};
console.log(add_all([2,5])); // 14
console.log(add_all([-2,1])); // -2
console.log(add_all([0,0])); // 0
// 13. True or False
function is_it_true(args) {
if(typeof(args) === "boolean") { // check if the type of the argument is a boolean
return true;
}
else {
return false;
}
};
console.log(is_it_true('false')); // false
console.log(is_it_true(false)); // true
console.log(is_it_true(1)); // false
console.log(is_it_true(true)); // true
// 14. Return Largest Numbers in Arrays
function largest_of_four(arr) {
if (arr.length === 0) {
return 'The array is empty'; // in case it's passed an empty array
}
else {
let largestnumbers = 0; // works only for an array with at least 1 positive number
let finalnumbers = [];
for (i = 0; i < arr.length; i++){ // for each array inside the inicial array
largestnumbers = 0;
for (j = 0; j < arr[i].length; j++) { // inside each individual array
if (arr[i][j] > largestnumbers) {
largestnumbers = arr[i][j];
}
}
finalnumbers.push(largestnumbers); // new array with the largest numbers of each individual array inside the inicial one
}
return finalnumbers;
}
};
console.log(largest_of_four([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])); // [27,5,39,1001]
console.log(largest_of_four([[-1, -5, -12, 2], [0, 1, 57, 0]])); // [2, 57]
// 15. Is it an anagram?
function isAnagram(test, original) {
if (test.length != original.length) {
return false
}
else{
return test.toLowerCase().split('').sort().join() === original.toLowerCase().split('').sort().join();
} // strig to lower case, split the string in letters into an array, sort array alphabetically, join it back into a string
};
console.log(isAnagram('foefet', 'toffee')); // true
console.log(isAnagram('days', 'aDys')); // true
console.log(isAnagram('huhuhu', 'huhu')); // false
console.log('Hello, World!')
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment