Tuesday, December 10

JavaScript String Manipulation (Solution to Code Challenge #12)

Last time on the code challenge #12 we looked at problems involving the use of String Manipulation techniques. Yet to try your hands at the challenge? You can check it out here.

You can also see other fantastic submissions in the Spectrum Chat. In this post, we shall be solving these awesome challenges and you know the best part? Chris did really cool videos to better explain these challenge solutions!

The Challenge

Manipulating strings form the basis of programming in JavaScript and is important both in simple logical instances to even more complex instances. In this challenge solution, we employed the use of functions in JavaScript as well as array and string methods.

The Base Pen

A base pen was provided for you to easily get started with the project. The pen consists of JavaScript code which was basically empty function definitions with descriptions for you to fill in your code.
Here is a sample of the base pen.

The Technique

As earlier stated, JavaScript functions, as well as JS string and array methods, were employed to solve this challenge. Also, things you would see in the solution are:

  • ES6 Syntax
  • Ternary Operators
  • Regular Expressions

Next, we shall go over each individual challenge. Whilst you see an overview of how it was solved, Chris provides an awesome and more detailed explanation in his video for each challenge.

Padded Number

In this challenge, we are required to pad individual numbers in an array such that single figures from 1-9 are padded with a preceding 0.

A padNumber() function is created, which utilizes a ternary operator to pad numbers less than 10. Subsequently, a .map() function is used to iterate over the array and apply padNumber to each number in the array.

// Pad given single numbers in array to look like "10", "05", "16", "02"
const nums = ['2', '4', '25', '10', '3'];
const padNumber = number => (+number < 10) ? `0${number}` : number;
const paddedNum = nums.map(padNumber);
console.log(paddedNum)

Camel to Title

The goal of this challenge is to convert a provided string from camelCase to Title Case.

In solving for this we took the following steps:

  1. Split the string into an array.
  2. Add a space before all uppercase letters using regex.
  3. Convert all text to lowercase and trim for spaces.
  4. Convert text array into a string and split back into an array.
  5. Filter array for blanks.
  6. Capitalize the first letter of each word.
  7. Join the array into a string.
// Convert a given sentence from camelCase to Title Case
const camelCaseText = "the simplestThings in LIFE are alwaysThe best"

const clean          = text => text.toLowerCase().trim();
const capitalize     = text => `${text[0].toUpperCase()}${text.slice(1)}`;
const splitOnCapital = text => text.replace(/([A-Z])/, (match, capture) => ` ${capture}`);
const noBlanks       = text => !!text

const titleCase = text => {
  return text
    .split(" ")
    .map(splitOnCapital)
    .map(clean)
    .join(' ')
    .split(' ')
    .filter(noBlanks)
    .map(capitalize)
    .join(" ")
}

console.log(titleCase(camelCaseText))

Title to Camel

In this challenge we’ll be converting text in titlecase to camelcase.

Note that words would be converted in pairs

To achieve this, we simply:

  1. Convert the sentence to lowercase and split into an array.
  2. Loop over every two words and create a camelcase pair off them.
  3. Push the pairs into an empty array.
  4. Convert the array to a string.
// Convert the Title Case back to camelCase
const newTitle = "These Words Should Go In Pairs"
const convertToCamel = text => {
  const words  = text.toLowerCase().split(" ")
  const newArr = []

  // loop over every 2 words and insert as camel_case pair
  for (i = 1; i <= words.length; i += 2) {
    const wordIndex = i - 1;
    const firstWord = words[wordIndex];
    let secondWord  = words[wordIndex + 1];    
    secondWord      = `${secondWord[0].toUpperCase()}${secondWord.slice(1)}` 

    newArr.push(`${firstWord}${secondWord}`);
  } 

  return newArr.join(" ")
}
console.log(convertToCamel(newTitle))

Passage Counter

For this challenge, we will be implementing a popular feature in several blogs which displays the time to read a piece of text.

Note: The average human reads 200 words per minute.

To solve this challenge we simply cleaned the passage, split the passage into an array of words the found the average time to read the passage taking into consideration the number of words a human reads per minute.

The resulting time is returned in minutes or seconds if less than a minute. All figures are rounded to whole numbers.

// How many seconds will it take to read the provided text? 
// If it goes past 60 seconds, quote in minutes!
const passage = `The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz. How quickly daft jumping zebras vex. Two driven jocks help fax my big quiz. Quick, Baz, get my woven flax jodhpurs! "Now fax quiz Jack!" my brave ghost pled. Five quacking zephyrs jolt my wax bed. Flummoxed by job, kvetching W. zaps Iraq. Cozy sphinx waves quart jug of bad milk.`

const timeToRead = text => { 
  const averageReadingTime = 200 // Humans read an average of 200 words per minute
  const cleanedPassage     = passage.split(" ").filter(el => el.trim() !== "")
  const timeInMinutes      = cleanedPassage.length / averageReadingTime;

  return timeInMinutes < 1 
    ? duration = `${Math.round(timeInMinutes * 60)}s` 
    : duration = `${Math.round(timeInMinutes)}mins`
}
console.log(timeToRead(passage))

Pig Latin

Pig latin is simply a word game or altered english which misplaces the position of letters in a word. See more on pig latin here.
The goal of this challenge is to convert a given word to pig latin. Here are the rules:

  • In words that begin with consonant sounds, all letters before the initial vowel are placed at the end of the word sequence. Then, “ay” is added.
  • When words begin with consonant clusters (multiple consonants that form one sound), the whole consonants before the vowel is added at the end followed by an “ay”.
  • In words that begin with vowel sounds, one just adds “ay” to the end.

To solve this, the following steps were taken:

  1. Create a regular expression which holds the 5 vowels.
  2. Find the index of the first vowel occurrence in the word.
  3. Create a main condition which verifies if the word starts with a vowel.
  4. Use a ternary operator to manipulate the word based on the truthy or falsy of the main condition.
// Convert any word to Pig Latin, see how to convert here => https://en.wikipedia.org/wiki/Pig_Latin
const word = "hamlet"
const pigLatin = word => {
  const vowel = /[aeiou]/i;
  const firstVowelIndex = word.indexOf(word.match(vowel)[0]);
  const startsWithVowel = firstVowelIndex === 0;

  return startsWithVowel
    ? `${word}ay`
    : `${word.slice(firstVowelIndex)}${word.substr(0, firstVowelIndex)}ay`;
}
console.log(pigLatin(word));

Here is the final product: https://codepen.io/Chuloo/pen/JBExxO

Conclusion

In this post, we have seen how JavaScript functions are utilized in manipulating strings and solving problems. Go ahead to try other possibly performant ways of solving the individual challenges. Feel free to leave any comments and suggestions in the comment section. Happy coding!


Source: Scotch.io

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x