I am doing this freecodecamp quest where I need to confirm the ending of a string.
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending/
And here is my code.
function a(str,target){
/*get rid of the whitespaces*/
let replaced = str.replace(/ /g,'');
console.log(replaced);
/*convert string into array*/
let array = replaced.split("");
console.log(array);
/*reverse it*/
let reversed = array.reverse();
console.log(reversed);
/* new array */
let new_array = reversed.slice(0,target.length);
console.log(new_array);
/*new target*/
let new_target = target.split("").reverse();
console.log(new_target);
if(new_array===new_target){
return true;
}
else{
return false;
}
}
console.log(a("hello world","world"));
Then I realised that === does not work on arrays.
I checked stackoverflow how to see whether two arrays are identical, here is the answer:
// Warn if overriding existing method
if(Array.prototype.equals)
console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});
Is this the only way to do this? It seems really complicated.
Or I should just compare string to string.