Functions into Functions explainer


#1

The aim of this puzzle: Use a different callback function in updateAllAndCheck()

Walkthrough of the solution: The checkPassport and updateAllAndCheck function definitions are already completed. The checkPassport function will take a string, check if it contains the string 'Passport' inside of it, and then prints whether whether it does or not. The updateAllAndCheck function runs a check on a string and then updates the string.

The updateAllAndCheck() function is called at the bottom of the code. It’s arguments are travelDocument, 'grasshoper', 'grasshopper', and checkLength. The important part is the 4th argument, checkLength, which is the name of another function. That makes checkLength a callback function. The callback should be changed to checkPassport.

Sample code solution:
(Tap below to reveal)

function checkPassport(string) {
  string.includes('Passport') ? console.log('This document is a passport') : console.log('This document is not a passport');
}

function updateAllAndCheck(string, oldPart, newPart, extraCheck) {
  extraCheck(string);
  return updateAllNames(string, oldPart, newPart);
}

console.log(travelDocument);
travelDocument = updateAllAndCheck(travelDocument, 'grasshoper', 'grasshopper', checkPassport);
console.log(travelDocument);

JavaScript Concepts: Callback Functions, Calling Functions, Code Block (function), console.log()

Additional Code
// travelDocument values
let passport = `Passport...
Name: grasshoper,
Country: ${pickRandom(['Andorra','Barbados','Cameroon','Denmark','Eritrea','Finland','Guyana','Honduras','Israel','Japan','Kosovo','Lebanon','Malta','Nigeria','Oman','Philippines','Qatar','Rwanda','Slovenia','Togo','Uzbekistan','Vietnam','Yemen','Zambia'])}`;

let hotel = `Hotel Reservation for grasshoper...
Room ${pickRandom(499)+100}`;

let rental = `Vehicle Rental for grasshoper...
Type: ${pickRandom(['economy','mid-size','full-size','premium','luxury','minivan','convertible','SUV','van'])},
License: ${[...Array(6)].map(i=>(pickRandom(36)-1).toString(36)).join('').toUpperCase()}`;

let ticket = `Plane Ticket for grasshoper...
Flight GH${pickRandom(8999)+1000},
Depart: ${pickRandom(12)}:${pickRandom(49)+10},
Arrive: ${pickRandom(12)}:${pickRandom(49)+10}`;

let travelDocument = pickRandom([passport, hotel, rental, ticket]);

// Functions
function checkLength(string) {
  string.length > 20 ? console.log('Username too long') : console.log('Username updated');
}

function updateAllNames(string, oldPart, newPart) {
  if (string.includes(oldPart) === false) {
    return string;
  }
  string = string.replace(oldPart, newPart);
  return updateAllNames(string, oldPart, newPart);
}