If first half of string = last half?

If first half of string = last half?
0

#1

Working on a problem here and need some help:

Instructions:

Write a function named repeats that returns true if the first half of the string equals the last half, and false if not

Example:

If you pass it "haha" then it should return true because "ha" (the first half) equals "ha" (the second half)
If you pass it "yay" then it should return false because it's odd
If you pass it "heehaw" then it should return false because "hee" doesn't equal "haw"
function repeats(str) {
    
    if(str.length % 2 !== 0) {
        return false;
    } else {
        string.length / 2
    }
        return true;
};

#2

Walk me through the logic in your current code (especially the else block of code).

You need think about an algorithm for that else.


#3

First If is good, rest you should discard.

  1. Determine if string cut in half doesn’t produce float. If it is, return false.
  2. If string cut in half doesn’t produce float, then cut string in half, proceed with comparing both halfs of string with each other. If that is correct also. return true.

#4

Thanks, will get around to it :slight_smile:


#5

HINT: One way way to solve this challenge is to think about a string method which allows you to compare a “slice” of the first half with a “slice” of the second half.


#6

Gonna attack it tomorrow, will ask then.


#7

Do I still write an else if in the second statement? Yes right?

I have this currently:

function repeats(str) {
    
    if(str.length % 2 !== 0) {
        return false;
    } else if (str.split('').length / 2) {
        
        
    }
        return true;
};

#8

Solved, but still very curious about your way @RandellDawson

function repeats(str) {
    
    if(str.length % 2 !== 0) {
        return false;
    }
    
    let first = str.substr(0, str.length / 2);
    let second = str.substr(str.length / 2);
    
    return first === second;
};

#9
const repeats = str => {
  const midPoint = str.length / 2;
  return str.slice(0, midPoint) === str.slice(midPoint);
};

You could do the same with your use of substr:

const repeats = str => {
  const midPoint = str.length /  2;
  return str.substr(0, midPoint) === str.substr(midPoint);
};

#10

Honestly, seeing your code all the time really inspires me to get better every day. Thanks a lot. Are slice and substr essentially the same for a string?