简体   繁体   中英

JavaScript function receives two strings and returns n

I've been trying to complete this challenge recently but with no success, tried many ways but for some reason I don't manage to complete all the examples below.

I will be appreciated if someone can assist me with that, showing me step by step.

Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned.

If the second string isn't a valid rotation of the first string, the method returns -1. Specification shiftedDiff(first, second) provide amount of rotations to match words

Parameters first: String - word to be matched

second: String - word to be checked

Return Value Number - Number of rotations, nil or -1 if invalid

Examples:

  • "coffee", "eecoff" => 2
  • "eecoff", "coffee" => 4
  • "moose", "Moose" => -1
  • "isn't", "'tisn" => 2
  • "Esham", "Esham" => 0
  • "dog", "god" => -1

 function shiftedDiff(first, second) { // Split the second word into an array for // easier manipulation const arr = [...second]; // Iterate over the array for (let i = 0; i < arr.length; i++) { // If the first and joined array match // return the index if (first === arr.join('')) return i; // Otherwise `shift` off the first element of `arr` // and `push` it on the end of the array arr.push(arr.shift()); } // If there are no matches return -1 return -1; } console.log(shiftedDiff('coffee', 'eecoff')); // 2 console.log(shiftedDiff('eecoff', 'coffee')); // 4 console.log(shiftedDiff('moose', 'Moose')); // -1 console.log(shiftedDiff("isn't", "'tisn")); // 2 console.log(shiftedDiff('Esham', 'Esham')); // 0 console.log(shiftedDiff('dog', 'god')); // -1

Documentation

 let shiftedDiff = (f, s) => { let r = -1; f.split('').forEach((e, i) => { f = f.substr(1) + e; if (f == s) r = f.length - (i + 1) }) return r; } console.log(shiftedDiff("coffee", "eecoff")) console.log(shiftedDiff("eecoff", "coffee")) console.log(shiftedDiff("moose", "Moose")) console.log(shiftedDiff("isn't", "'tisn")) console.log(shiftedDiff("Esham", "Esham")) console.log(shiftedDiff("dog", "god"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM