Advertisement
Guest User

Untitled

a guest
May 25th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. //Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.
  2. //(ignoring case)
  3.  
  4. //MY CONVOLUTED SOLUTION
  5. function mutation(arr) {
  6. //convert each array element to a separate string and change to lowercase
  7. let str1 = arr[0].toLowerCase();
  8. let str2 = arr[1].toLowerCase();
  9. //create new array for comparison
  10. let newArr = [];
  11. //search for second string characters in first string
  12. for (let i = 0; i < str2.length; i++){
  13. if (str1.indexOf(str2[i]) != -1){
  14. //add second string characters to array only if they're found in first string
  15. newArr.push(str2[i]);
  16. }
  17. }
  18. //join array elements into one string
  19. newArr = newArr.join('');
  20. //compare
  21. return newArr == str2;
  22. }
  23.  
  24. mutation(["Alien", "line"]);
  25.  
  26. //MY REFACTORED SOLUTION (based on suggested solution)
  27. function mutation(arr) {
  28. //convert each array element to a separate string and change to lowercase
  29. let str1 = arr[0].toLowerCase();
  30. let str2 = arr[1].toLowerCase();
  31. //search for second string characters in first string
  32. for (let i = 0; i < str2.length; i++){
  33. //return false if a second string character isn't found in first string
  34. if (str1.indexOf(str2[i]) < 0){
  35. return false;
  36. }
  37. }
  38. //return true if all second string characters are found in first string
  39. return true;
  40. }
  41. mutation(["Alien", "line"]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement