Functions Exercise

Javascript functions exercise

by Mehmetcan Sinir

JavaScript

//exercise 1 reversing a number:
function reverseANumber(n) {
    n = n + "";
    var k = n.split("").reverse().join("");
    alert(k);
}


//exercise 2
//check if a passed string is a palindrome (reads the same backwards) or not

function palindrome(word) {
    var firstOne = word.toLowerCase().split(""); //split it into an array
    //remove all the white space
    for (var i = 0; i < firstOne.length; i++) {
        if (firstOne[i] == " ") {
            firstOne.splice(i, 1);
        }
    }
    //reverse the array and rejoin to get the reverse word 
    var secondOne = firstOne.reverse().join("");
    console.log(secondOne);
    //rejoin original array;
    firstOne = firstOne.join("");
    console.log(firstOne);
    //check if it is a Palindrome
    if (firstOne == secondOne) {
        console.log("the word " + word + " is a palindrome");
        return word;
    } else {
        console.log("the word " + word + " is not a palindrome");
        return word;
    }
}

palindrome("A but tuba");

//write a function that generates all combinations of a string

function allCombinations(word) {
    var firstArray = word.split("");
    var empty = []; //create an empty array for the results
    for (var sti = 0; sti < firstArray.length; sti++) {
        for (var i = 0, k = 0; i <= firstArray.length; i++) {
            empty[k] = firstArray.slice(sti, i);
            var combination = empty[k].join("");
            if (combination != "") {
                console.log(combination);
            }
            k++;
        }
    }
}

allCombinations("try");

//sorting a word
function sorting(word) {
    var ourArray = word.split("");
    var sortedWord = ourArray.sort().join("");
    console.log(sortedWord);
}

sorting("webmaster");

//Write a JavaScript function that accepts a string as a parameter and counts the number of vowels within the string

function vowelCounter(word) {
    var ourArray = word.split("");
    var number = 0;
    var vowelList = "aeiouAEIOU";
   ...