Algorithm Digest #2

Here we are going to explain 5 algorithms

Algorithm #1

Confirm the Ending

Check if a string (first argument, str) ends with the given target string (second argument, target).



/**
 * Confirm the Ending
Check if a string (first argument, str) ends with the given target string (second argument, target).

This challenge can be solved with the .endsWith() method, which was introduced in ES2015. 
But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead.


 */

/*
function confirmEnding(str, target) {
  if (str.endsWith(target)) return true
  return false;
}
*/

 function confirmEnding(str, target) {
  return str.slice(str.length - target.length) === target;
}

confirmEnding("Bastian", "e");

Algorithm #2

Finders Keepers


/**
 * 
 * Finders Keepers
Create a function that looks through an array arr and returns the first element in it that passes a 'truth test'. 
This means that given an element x, the 'truth test' is passed if func(x) is true. 
If no element passes the test, return undefined.
 */
 function findElement(arr, func) {
    let num = 0;
    for (let i = 0; i < arr.length; i++) {
      num = arr[i];
      if (func(num)) {
        return num;
      }
  
    }
    return undefined;
  }
  
  findElement([1, 2, 3, 4], num => num % 2 === 0);

Algorithm #3

Repeat a String

Repeat a given string str (first argument) for num times (second argument).



/**
 * Repeat a String Repeat a String
Repeat a given string str (first argument) for num times (second argument). 
Return an empty string if num is not a positive number. For the purpose of this challenge, 
do not use the built-in .repeat() method.


 */

function repeatStringNumTimes(str, num) {
    let repeatStr='';
    if (num <= 0) repeatStr = '';
    for (let i = 0; i < num; i++) {
        repeatStr += str;
    }
    console.log(repeatStr);
    return repeatStr;
}

repeatStringNumTimes("abc", 3);

Algorithm #4

Truncate a String

Truncate a string (first argument) if it is longer than the given maximum string length (second argument).



/**
 * Truncate a String
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). 
Return the truncated string with a ... ending.
 */

function truncateString(str, num) {
    return str.length > num ? str.slice(0, num) + "..." : str;
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);

Algorithm #5

Boo who

Check if a value is classified as a boolean primitive. Return true or false.



/**
 * Boo who
Check if a value is classified as a boolean primitive. Return true or false.

Boolean primitives are true and false.
 */

function booWho(bool) {
    return typeof bool==="boolean"
  }
  
  booWho(true);

Leave a Reply

Your email address will not be published. Required fields are marked *