Javascript
by Juan Manuel González Garzón
function countChars(word, c) {
let answer = 0;
for (let i = 0, n = word.length; i < n; ++i) {
if (String(word[i]) === c) answer++;
}
return answer;
}
// countChars("lol", 'l');
function isPalindrome(word) {
for (let i = 0, n = word.length / 2; i < n; ++i) {
if (String(word[i]) !== String(word[word.length - i - 1])) {
return false;
}
}
return true;
}
// isPalindrome('lolol');
// isPalindrome('lolol--');
/*
For the following sequence of integers, write a function that will find the three consecutive integers that add up to the highest sum. The Answer is 2586 for subarray [ 876, 903, 807 ]
491 846 835 202 863 336 372 992 39 211 561 282 900 270 428 267 333 363 568 680 649 692 953 159 290 31 832 302 179 587 340 286 90 442 447 641 920 219 136 966 255 647 885 753 415 982 205 779 468 752 882 814 332 702 92 15 876 903 807 234 73 998 927 80 275 353 544 342 716 215 374 504 799 784 842 66 991 738 456 455 43
*/
let integers = [
491, 846, 835, 202, 863, 336, 372, 992, 39, 211, 561, 282, 900, 270, 428, 267,
333, 363, 568, 680, 649, 692, 953, 159, 290, 31, 832, 302, 179, 587, 340, 286,
90, 442, 447, 641, 920, 219, 136, 966, 255, 647, 885, 753, 415, 982, 205, 779,
468, 752, 882, 814, 332, 702, 92, 15, 876, 903, 807, 234, 73, 998, 927, 80,
275, 353, 544, 342, 716, 215, 374, 504, 799, 784, 842, 66, 991, 738, 456, 455,
43,
];
let Answer = class Answer {
constructor(sum, numbers) {
this.sum = sum;
this.numbers = numbers;
}
// Methods
*getSum() {
return this.sum;
}
*getNumbers() {
return this.numbers;
}
};
let answers = [];
for (let i = 0; i < integers.length; i++) {
let sum = integers[i] + integers[i + 1] + integers[i + 2];
let numbers = [integers[i], integers[i + 1], integers[i + 2]];
let answer = new Answer(sum, numbers);
answers.push(answer);
}
let max = 0;
let answer = {};
for (let i = 0; i < answers.length; i++) {
if (answers[i].sum > max) {
max = answers[i].sum;
answer = answers[i];
}
}
console.log(answer);
let Vs var
// El alcance de una variable var es la función contenedora
function varTest() {
var x = 31;
if (true) {
var x = 71; // ¡misma variable!
console.log(x); // 71
}
console.log(x); // 71
}
function letTest() {
let x = 31;
if (true) {
let x = 71; // variable diferente
console.log(x); // 71
}
console.log(x); // 31
}
// llamamos a las funciones
varTest();
letTest();
// En el nivel superior de un programa y funciones, let , a diferencia de var, no crea una propiedad en el objeto global, por ejemplo:
var x = "global";
let y = "global";
console.log(this.x); // "global"
console.log(this.y); // undefined