Sesión: Cierre de los 30 días de JavaScript

Clase 99 de 9930 días de JavaScript

Resumen

Aprende a construir un array en JavaScript desde cero y domina métodos clave sin depender de los nativos. Aquí verás cómo implementar map, filter, join, push, pop, shift y unshift, entender por qué los arrays son objetos y repasar for in vs for of. Además, toma nota de la fecha límite: 30 de abril y cómo asegurar tus comunicaciones.

¿Qué pasó con los treinta días de JavaScript y cuál es la nueva fecha límite?

La comunidad acordó extender el reto. La fecha límite es el 30 de abril. Esto da margen para completar los días pendientes y cerrar con examen y certificado.

  • Faltan días por liberar: día 24 (con playgrounds reestructurados), 27, 28, 29 y 30. Los contenidos ya están en revisión y ajustes de tests.
  • Si no te llegan emails: escribe a team@platzi.com con asunto: recibir mails de los retos. Explica que quieres las comunicaciones del reto.
  • Canales de seguimiento: correo y Discord. Ambos cuentan.
  • Requisitos para mentorías: 80 % de playgrounds/lecturas/quizzes y examen aprobado.
  • Examen: si fallas, puedes repetir. Tiempo de espera: 6 horas entre intentos.
  • Participación en redes: usa el hashtag treinta días JS Platzi. Hay una sorpresa para quienes han estado activos.
  • Próximo reto: se está preparando treinta días de Python. Compromiso anunciado: todos los ejercicios estarán disponibles desde el día 1.

¿Qué habilidades y conceptos practicarás al crear una clase de array?

El desafío pide implementar una clase que funcione como un array nativo sin usar sus métodos. Esto refuerza fundamentos de estructuras de datos y del lenguaje.

  • Arrays como objetos: manejar claves numéricas en un objeto this.data y un contador this.length.
  • Métodos a implementar: map, filter, join, push, pop, shift, unshift.
  • Buenas prácticas: retornos correctos (por ejemplo, push retorna el nuevo length), cuidado con valores falsy como 0, y lectura de tests.
  • Puente hacia más temas: se mencionan stacks, queues, singly linked list y doubly linked list para días posteriores.

¿Cómo se implementan push y map sin arrays nativos?

  • Idea clave: almacenar elementos en this.data usando índices y controlar this.length manualmente.
class MyArray {
  constructor() {
    this.data = {}; // objeto como contenedor indexado.
    this.length = 0; // contador de elementos.
  }

  push(item) {
    this.data[this.length] = item; // agrega al final.
    this.length += 1;               // actualiza length.
    return this.length;             // como el nativo.
  }

  map(fn) {
    const res = new MyArray();
    for (let i = 0; i < this.length; i++) {
      const element = this.data[i];
      res.push(fn(element));
    }
    return res; // retorna un nuevo array.
  }
}
  • Clave de aprendizaje: no usar corchetes del array nativo, pero sí claves numéricas en el objeto interno.

¿Cómo filtran y concatenan filter y join?

  • filter: ejecuta una condición por elemento y retorna un nuevo contenedor solo con los que la cumplen.
filter(fn) {
  const res = new MyArray();
  for (let i = 0; i < this.length; i++) {
    const el = this.data[i];
    if (fn(el)) res.push(el);
  }
  return res;
}
  • join: concatena todos los elementos con un separador. Evita agregar el separador al final.
join(sep = ",") {
  let out = "";
  for (let i = 0; i < this.length; i++) {
    out += this.data[i];
    if (i < this.length - 1) out += sep; // sin separador extra.
  }
  return out;
}

¿Qué hacen pop, shift y unshift en tu estructura?

  • pop: retorna el último elemento y reduce el length.
pop() {
  if (this.length === 0) return undefined;
  const lastIndex = this.length - 1;
  const last = this.data[lastIndex];
  delete this.data[lastIndex];
  this.length -= 1;
  return last;
}
  • shift: elimina el primer elemento, recorre todo a la izquierda, borra el último duplicado y reduce el length. Retorna el elemento eliminado.
shift() {
  if (this.length === 0) return undefined;
  const first = this.data[0];
  for (let i = 0; i < this.length - 1; i++) {
    this.data[i] = this.data[i + 1];
  }
  delete this.data[this.length - 1];
  this.length -= 1;
  return first;
}
  • unshift: desplaza a la derecha e inserta al inicio. Estrategia efectiva: iterar de derecha a izquierda, abrir espacio en 0 y asignar.
unshift(item) {
  for (let i = this.length; i > 0; i--) {
    this.data[i] = this.data[i - 1];
  }
  this.data[0] = item;
  this.length += 1;
  return this.length;
}

Punto crítico: cuidar casos como item igual a 0 y el orden de las operaciones para no sobrescribir valores.

¿Cuándo usar for in y for of en JavaScript?

Regla práctica: for of itera valores; for in itera índices o claves.

  • En arrays: for of entrega elementos; for in entrega índices.
const arr = [1, 2, 3];
for (const v of arr) console.log(v); // 1, 2, 3.
for (const k in arr) console.log(k); // '0', '1', '2'.
  • En objetos: for in recorre claves. Para valores usa Object.values con for of.
const obj = { live: 'cierre del live', students: 100000 };
for (const k in obj) console.log(k); // 'live', 'students'.
for (const v of Object.values(obj)) console.log(v); // 'cierre del live', 100000.

¿Tienes dudas sobre la implementación o sobre el reto, el examen, las mentorías o los playgrounds? Cuéntame en los comentarios qué parte te costó más y qué te gustaría ver en treinta días de Python.

      Sesión: Cierre de los 30 días de JavaScript