Four Javascript problems solved in one Monster Post

Last week I solved all the 20 problems of a Javascript Challenge on FreeCodeCamp and damn, I feel satisfied already but I know there's still a lot to go, I am still just at the beginning, just a few steps away from the finish line, but at least I already advanced some distance, right?

This is the first time I'm using @ecency to write a post and I'm not sure how I'll feel about it. Over the past 4 years most of my posts were written on hive.blog and actifit although I did use esteem a few times to publish my crap so I'm not a newbie when it comes to using other platforms.

As with every post related to coding, I'll update my How long does it take to become a developer table so you get an idea how much time I've spent learning and also, in case you want to become a dev yourself, you get a general idea of how much sweat, tears, blood and time you should consider giving to this life project.

ConceptTime spent
Researching Howto8 hours
Downloading programs2 hours
Learning Javascript46 hours (so far)

The Problems

A small index in case you want to know what the problems are about:

  • Truncate string
  • Chunky Monkey - Split an array into groups of a size and return them as a two dimensional array.
  • Slasher - Return the remaining elements of an array after chopping off n elements from the head.
  • Mutations - Return true if the first element of the array contains all of the letters of the string in the second element of the array.

Down to business

Truncate string

We have to truncate a string (first argument) if it is longer than the given maximum string length (second argument). Then we have to return the string with a "..." ending.

Inserting the "..." will add to the string length.

If the given max string length "num" is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string.

function truncateString(str, num) {
    if (num <= 3) return str.slice(0, num) + "...";
}


console.log (truncateString("The tiger jumped rapidly", 3))
//output: "The..."

But this code is not complete because it doesn't work if the num is larger than the num, we need more parameters.

function truncateString(str, num) {
    if (num <= 3) return str.slice(0, num) + "...";
    return str.slice(0, num-3) + "..."; 
// what we are doing here is just giving it an implicit "else" statement that, if the above "if" doesn't run, the second return runs. 
// We add the "-3" because remember the "..." add to the length of the string, so we need to take that into account
}


console.log (truncateString("The tiger jumped rapidly", 11))

We can add another statement for when the string is shorter than the given max string length.

function truncateString(str, num) {
    if (num >= str.length) return str;
    if (num <= 3) return str.slice(0, num) + "...";
    return str.slice(0, num-3) + "...";
}

console.log (truncateString("The tiger jumped rapidly", 25))

Chunky Monkey

Write a function that splits an array (First argument) into groups the length of "size"(second argument), and returns them as a two dimensional array.

function chunkyArrayInGroups(arr, size) {
    var groups = []; 
    while (arr.length > 0) {


    } 
// We will use a while loop instead of a for loop, it just makes more sense because a for loop is trickier for problems like this one.
    return groups;
}

chunkyArrayInGroups(["a", "b", "c", "d"], 2);

If we run the code like this, the loop will go on forever because we don't have parameters yet for the while loop so the code is not ready.

function chunkyArrayInGroups(arr, size) {
    var groups = []; 
    while (arr.length > 0) {
        groups.push(arr.slice(0, size));        // We need to make something happen inside the while loop that makes the array.length go to zero so the loop can stop. 
// Above, we push something into groups every single loop. We push a sliced element or a sliced group of elements. What determines the length of it is the 2 (second parameter).
    }            
    return groups;
}

chunkyArrayInGroups(["a", "b", "c", "d"], 2);

So now we are pushing the elements of the array into a nested array but, we still need to get rid of the elements we already pushed in the original array, that way, the condition "arr.length > 0" stops being true at some point.

function chunkyArrayInGroups(arr, size) {
    var groups = []; 
    while (arr.length > 0) {
        groups.push(arr.slice(0, size));
        arr = arr.slice(size);      // what we do here is making the original array smaller in size after every loop.
    }            
    return groups;
}

chunkyArrayInGroups(["a", "b", "c", "d"], 2);

And the code is done.

There is a simpler way of doing this, using the method .splice, which actually removes the elements it takes into the nested array, leaving the original array without the elements it took:

function chunkyArrayInGroups(arr, size) {
    var groups = []; 
    while (arr.length > 0) {
        groups.push(arr.splice(0, size));
    }            
    return groups;
}

console.log (chunkyArrayInGroups(["a", "b", "c", "d"], 2));

Slasher

Return the remaining elements of an array after chopping off "n" elements from the head.

It's a function that will determine how many items should we delete from the array and return the remaining items.

function slasher(arr, howMany) {
    arr.splice(0, howMany);
    return arr;

}

console.log(slasher([1,2,3,4,5,6,7],2));

Note to self: Splice works as follows:

var arr = ["a", "b", "c", "d"];

console.log(arr.splice(0, 2));
console.log(arr)

// Output: ["a","b"] and the original array will then be ["c","d"]

Whereas slice works as follows:

var arr = ["a", "b", "c", "d"];

console.log(arr.slice(0, 2));
console.log(arr)

// Output: [ 'a', 'b' ] and the original array will remain [ 'a', 'b', 'c', 'd' ]

Mutations

Return true if the string in the first element of the array contains all of the letters os the string in the second elemenet of the array.

For example, ["hello", "Hello"], should return true because all of the letters in the second string are present in the first, ignoring case.

The arguments ["hello", "hey"], should return false because the string "hello" does not contain a "y".

Lastly, ["alien", "line"], should return true because all of the letters in "line" are present in "Alien".

function mutation(arr) {
    var firstWord = arr[0].toLowerCase();
    var secondWord = arr[1].toLowerCase();
    // This way we are storing each element of the array in a diferent variable so that we can play with them later. We are also converting them into an only lower case strings.

    for (var i=0; i<10; i++) {
        console.log(i);
    }
}

console.log(mutation(["hello", "hey"]));

The basic code is written, but we don't want to loop from 0 to 9, we want to loop through the words, right? so...

function mutation(arr) {
    var firstWord = arr[0].toLowerCase();
    var secondWord = arr[1].toLowerCase();

    for (var i=0; i<secondWord.length; i++) {
        console.log(secondWord[i])
    }
}

mutation(["hello", "hey"]);

Note to self: Index of method works as follows

var greeting = "hello"
console.log(greeting.indexOf("e")) 
// Output: 1 ----- If we ask for the index of a letter that doesn't exist (LIKE Z) it will output -1

Using the .indexOf method we can then loop through each of the indexes of the second word and check if they exist in the first word.

function mutation(arr) {
    var firstWord = arr[0].toLowerCase();
    var secondWord = arr[1].toLowerCase();

    for (var i=0; i<secondWord.length; i++) {
        if (firstWord.indexOf(secondWord[i]) === -1) return false; 
        }
        return true;
}

console.log(mutation(["hello", "hey"]));            // false
console.log(mutation(["hello", "he"]));             // true

Note for the above: If the current letter of the index does not exist in the first word, just return false, we don't have to check further. If the loop is done and we have already checked every index (letter) of the second word in the first word and it doesn't return false on any loop, return true, because it means that if we didn't have false, it means all the letters in the second word exist in the first word.

There is another way of doing this, a much simpler way now that we understand the logic behind the code, using "letter of"

function mutation(arr) {
    var firstWord = arr[0].toLowerCase();
    var secondWord = arr[1].toLowerCase();

    for (var letter of secondWord) {
        if (firstWord.indexOf(letter) === -1) return false;

    }
    return true;
}


console.log(mutation(["hello", "hey"]));            // false
console.log(mutation(["hello", "he"]));             // true

There is yet another method of solving this, using .includes

function mutation(arr) {
    var firstWord = arr[0].toLowerCase();
    var secondWord = arr[1].toLowerCase();

    for (var letter of secondWord) {
        if (!firstWord.includes(letter)) return false;      // If first word DOES NOT (!) include letter, then return false.
    }
    return true;
}


console.log(mutation(["hello", "hey"]));            // false
console.log(mutation(["hello", "he"]));             // true

And damn, we are done. Formatting this post was trouble enough, imagine how much trouble I went through to actually solve the problems!

Anyway, I hope you found the solving of this problems useful or at least you found the little table at the beginning a bit informative.

If not, well, I don't mind, I'm way too obsessed with Javascript at the moment that I won't hold it against you or hate you :D

H2
H3
H4
3 columns
2 columns
1 column
2 Comments