Home > Enterprise >  Adding method to prototype string but want does this method mean
Adding method to prototype string but want does this method mean

Time:04-17

I am trying to understand what this mean?
What I am thinking is that phrase will pass a part of array, so this in this case eve to phrase.palindrome method. That method will take and run it through. First var len takes eve and remove 1 from it using length -1. This results in var len being assigned number two as the length of eve is 3. Now for is in use, so var i = 0; i <= len/2; i .
now becomes var i = 1;1 <= 1; i ."is this correct"
I don't understand what going on here:

    for (var i = 0; i <= len/2; i  ) {
        if (this.charAt(i) !== this.charAt(len-i)) {
            return false;

Here is all of the the code:

String.prototype.palindrome = function() {
    var len = this.length-1;
    for (var i = 0; i <= len/2; i  ) {
        if (this.charAt(i) !== this.charAt(len-i)) {
            return false;
        }
    }
    return true;
};

var phrases = ["eve", "kayak", "mom", "wow", "Not a palindrome"];

for (var i = 0; i < phrases.length; i  ) {
    var phrase = phrases[i];
    if (phrase.palindrome()) {
        console.log("'"   phrase   "' is a palindrome");
    } else {
        console.log("'"   phrase   "' is NOT a palindrome");
    }
 }

CodePudding user response:

The code is essentially iterating through the string from both directions, comparing the first and last characters (indexes 0 and len) then the second from first and second from last and so forth until you reach the middle. A word is a palindrome if and only if the first and last characters are the same and the second and second to last characters are the same and so forth.

Note, there is something very wrong with this code. While it is technically possible to mutate the prototypes of built-in types in Javascript you should never, ever, ever do it. You gain no functionality you wouldn't from a normal function, while badly violating the principle of least surprise. Treat all types from other libraries, including built ins as if they are closed for modification and open for extension.

CodePudding user response:

I think this line has error:

for (var i = 0; i <= len/2; i  ) {

Beacuse somethimes length can be 3,5,7... and that can be problem.

I added some using examples:

for (var i = 0; i <= Math.floor(len / 2); i  ) {
// That same thing with floor in positive numbers, but in negative numbers that works like ceil.
for (var i = 0; i <= ~~(len / 2); i  ) {
// That same thing with floor, we can think like this pollyfill of floor.
for (var i = 0; i <= ~~(len / 2)   (Math.abs(len)>len?-1:0); i  ) {
  • Related