No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Aprende todo un fin de semana sin pagar una suscripción 🔥

Aprende todo un fin de semana sin pagar una suscripción 🔥

Regístrate

Comienza en:

5D
12H
4M
49S

Playground: crea tu propia implementación de unshift

7/29

Aportes 25

Preguntas 1

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

o inicia sesión.

Aqui les suministro mi solucion al reto
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

export class MyArray {
  constructor() {
    this.length = 0;
    this.data = {};
  }
  
  unshift(item){
    // Tu código aquí 👈 
    if (!item) {
      return this.length
    }
    if (this.length !== 0) {
      for (let i = this.length - 1; i >= 0; i--) {
        this.data[i + 1] = this.data[i];
      }
    }

    this.data[0] = item;
    this.length++;
    return this.length
  }
}

Mi solución fue:
*
*
*
*
*
*
Alerta Spoiler!
*
*
*
*
*
*

unshift(item) {
    if (item) {
      for (let i = this.length; i > 0; i--) {
        this.data[i] = this.data[i - 1];
      }
      this.data[0] = item;
      this.length++;
    }
    return this.length;  
  }

Mi solución

  unshift(item) {
    if (item) {
      this.length = 1;
      Object.values(this.data).forEach(el => {
        this.data[this.length++] = el;
      });
      this.data[0] = item;
    }
    return this.length;
  }

Siento que me compliqué mucho con los if, pero pues quedó cx

unshift(item) {
    if (this.length === 0 && item) {
      this.data[0] = item;
      this.length++
      return this.length;
    }
    else if (this.length != 0 && item) {
      for (let i = this.length; i > 0; i--) {
        this.data[i] = this.data[i - 1];
      }
      this.data[0] = item;
      this.length++;
      return this.length;
    }
    else if (!item) {
      return this.length;
    }
  }
}

No entiendo porqué en este ejercicio me dice que está mal mi codigo, pero si lo ejecuto en el inspector del navegador se ejecuta sin problemas

Les comparto el codigo para que lo comprueben

< for (let i = this.length; i > 0; i--){
                this.data[i] = this.data[i - 1]
            }  
            this.data[0] = item
            this.length++
            return this.data
        }> 

Yo lo solucioné de la siguiente manera:

  unshift(item){
    for (let key of Object.keys(this.data).reverse()) {
      this.data[new Number(key) + 1] = this.data[key];
    }
    this.data[0] = item;
    return this.length++;
  }
export class MyArray {
  constructor() {
    this.length = 0;
    this.data = {};
  }
  
  unshift(item) {
    this.length++;
    for (let i = this.length - 1; i > 0; i--) {
      this.data[i] = this.data[i - 1];
    }
    this.data[0] = item;
    return this.length - 1;
  }
}

La idea estaba bien pero no me funcionaba, había una prueba que no pasaba. Me puse a hace debug línea por línea y el error estaba al momento de asignar el valor de copyData, que lo estaba haciendo como se muestra debajo. (Cuando modificaba el data se modificaba también el copyData)

const copyData = this.data;

Solución

export class MyArray {
  constructor() {
    this.length = 0;
    this.data = {};
  }
  
  unshift(item){
    // Tu código aquí 👈
    if (item) {
      if (this.length > 0) {
        const copyData = {...this.data};
        for (let i = 1; i <= this.length; i++) {
          this.data[i] = copyData[i - 1];
        }
      }    
      this.data[0] = item; 
      this.length++;
    }    
    return this.length;
  }
}

Nota: (También se puede hacer recorriendo el arreglo de atrás hacia delante)

Mi aporte…! 😃

class MyArray {
constructor() {
this.length = 0;
this.data = {};
}

unshift(item) {
// Tu código aquí 👈
if (!item) {
return this.length
} else {
for (let i = this.length; i >= 0; i–) {
this.data[i] = this.data[i - 1];
}
this.data[0] = item;
this.length++
return this.length;
}
}
}

Les comparto mi solución. Realizada pensando en un código más modular o funcional. Espero les sea de ayuda

export class MyArray {
  constructor() {
    this.length = 0;
    this.data = {};
  }
  
  unShiftIndex() {
    for (let i = this.length - 1; i >= 0; i--) {
      this.data[i + 1] = this.data[i];
    }
    this.length++;
  }

  unshift(item) {
    if (item) {
      if (this.length == 0) {
        this.push(item)
      } else {
        this.unShiftIndex();
        this.data[0] = item;
      }
    }
    return this.length
  }

  push(item) {
    this.data[this.length] = item;
    this.length++;
    return this.data;
  }
}
//Mi solución :)
    unshift(item){
            for (let i = this.length; i > 0; i--){
            this.data[i] = this.data[i-1]
            }
            this.data[0] = item;
            const fisrtItem = this.data[0];
            this.length++;
            return fisrtItem;   
        } 

Hola que tal! quisiera saber si alguien me podria decir que estoy haciendo mal en el codigo?
export class MyArray {
constructor() {
this.length = 0;
this.data = {};
}

unshift(item){
if (!item) {
return this.length
}
else {
for (let i = this.data.length - 1; i <= 0; i–){
if (item != this.data[i]) {
this.data[i].length = item

    }
  }
}

}
}

corre todo normal pero en las pruebas sale

export class MyArray {
  constructor() {
    this.length = 0;
    this.data = {};
  }

  unshift(item) {
    for (let i = this.length; i >= 0; i--) {
      if (this.data[i - 1]) {
        this.data[i] = this.data[i - 1]
      } else {
        this.data[0] = item;
      }
    }
    this.length++;
    return this.length;
  }
}

expect(received).toEqual(expected) // deep equality

Expected: 0
Received: 1

expect(received).toEqual(expected) // deep equality

Expected: 5
Received: 6

quiero manejar la parte de la memoria, pero ahi va la mia
*
*
*
*
*
*
*

 unshift(item){
    if (item) {
      const auxData = { ...this.data }
      console.log(auxData)
      for (let i = 0; i < this.length; i++) {
        this.data[i + 1] = auxData[i]
        console.log(i, auxData[i])
      }
      this.data[0] = item;
      this.length++;
      return this.data
    }
    return this.length
  }```

mi solucion :

export class MyArray {
  constructor() {
    this.length = 0;
    this.data = {};
  }

  unshift(item) {
    if (!item) return this.length;
    //debo correr los item una pos adelante
    let count = this.length - 1; // variable auxiliar
    for (let i = this.length; i >= 0; i--) {
      this.data[i] = this.data[count];
      count--;
    }
    //ahora que corri los items una pos , reasigno el valor de la prop con index 0
    this.data[0] = item;
    //incremento en uno la longitud, porque aumente en uno la pos y agruege nuevo item
    this.length += 1;

    return this.length;

  }
}

Aquí dejo mi solución

Estas cerca!!
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
Ya casi!!
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
No necesitas ayuda, tu puedes hacerlo, yo creo en ti 💚
Nunca pares de aprender

Hola, comparto mi solución…











export class MyArray {
  constructor() {
    this.length = 0;
    this.data = {};
  }

  unshift(item) {
    if (item) {
      this.data[this.length] = this.data[this.length - 1];
      for (let i = this.length; i > 0; i--) {
        this.data[i] = this.data[i - 1];
      }
      this.data[0] = item;
      this.length++;
    }
    return this.length;
  }
}

Acá comparto una solución alterna
👇
👇
👇
👇
👇
👇
👇
👇
👇
👇

unshift(item){
    if (item) {
      for (let i = this.length; i >= 0; i--) {
        if (i == 0) {
          this.data[i] = item;
          this.length++;
          break;
        } else {
          this.data[i] = this.data[i - 1];
        }
      }
    }
    return this.length;
  }
unshift(item){
    if (!item) return this.length;

    for (let i = this.length; i > 0; i--) {
      this.data[i] = this.data[i - 1];
    }
    this.data[0] = item;
    return ++this.length;
  }

Aqui les comparto mi solucion por si a alguien le sirve

class MyArray {
    constructor() {
      this.length = 0;
      this.data = {};
    }
    
    unshift(item){
      for (let i = this.length; i > 0 ; i--) {
        this.data[i] = this.data[i - 1];    
      };
      this.data[0] = item;
      this.length++;
      ;
    return this.data;
  }
}

  const array = new MyArray();

  array.unshift('quinto');
  array.unshift('cuarto');
  array.unshift('tercero');
  array.unshift('segundo');
  array.unshift('primero');
  console.log(array.data);

De los mejores Playgorund que he hecho hasta el momento.

  unshift(item){
    if (item) {
      // condicional para ver si ya hay elementos dentro de data
      if (this.length) {
        // nueva variable para trabajar con el valor de length pero sin modificarlo
        let newIndex = this.length;
        for (let i = 0; i < this.length; i++){
          //corro los elementos una unidad al frente para dejar la posicion 0 disponible
          this.data[newIndex] = this.data[newIndex - (1)];
          newIndex--;
        }
      }
      //asigno el nuevo elemento al inicio y aumento el length
      this.data[0] = item;
      this.length++;
      return this.data;
      
    } else {
      // en caso que no hayan enviado ningun elemento
      return this.length;
    }
  }

Les comparto la solución con comentarios que utilicé

Para mi fue importante usar las llaves o “keys” del objeto que guarda los datos. utilizar “this.data.length” no se me permitía porque length es usado para arrays, y no para objetos.

Fue clave utilizar esta linea:

let keys = Object.keys(this.data);

Ahora si va toda la solución:

export class MyArray {
    
    // Me dice el tamaño y los datos que guarda la instancia de la clase
    // Inicia el tamaño en cero y el objeto que guarda los datos inicia vacio
    constructor() {
      this.length = 0;
      this.data = {};
    }
    
    unshift(item){
      // Tu código aquí 👈  
      // Si no se envia item, entonces devuelve el tamaño actual
      if (!item) return this.length; 

        // Obtengo las llaves del objeto que guarda los datos
      let keys = Object.keys(this.data);

        // Cuento cuantas llaves tiene el objeto para conocer su tamaño
      let objectSize = keys.length;

        // Verifico si el objeto tiene datos
      if ( objectSize > 0) {
        // Este ciclo for me permite liberar la primera posición del objeto
        // "El tercer elemento pasa a ser el cuarto, el segundo pasa a ser el tercero, y asi sucesivamente hasta llegar al primer elemento"
        for (let actualElement = objectSize; actualElement >= 0; actualElement--){
          this.data[actualElement] = this.data[actualElement - 1];
        }
      } 
  
      // El primer elemento tendré el valor del item que me envian
      // Se encuentra fuera del condicional para cubrir el escenario cuando el objeto está vacio y no es necesario reordenar nada y solo se ingresa el primer valor
      this.data[0] = item;
      //Aumento el tamaño en 1
      this.length += 1;
      // Devuelvo el valor del tamaño
      return this.length;
    }
  }
  

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Mi solución al reto; en consola corre a la perfección, sin embargo aquí en el playground me sale error porque asume que no le doy el bloque condicional para saber si this.lenght === 0 (cosa que me parece innecesaria):

class MyArray2 {
    constructor() {
      this.length = 0;
      this.data = {};
    }
    
    unshift(item){
            for (let i = 0; i < this.length; i++) {
                this.data[this.length - i] = this.data[this.length - i - 1];
            }
            this.length++; 
            this.data[0] = item;
            return this.length
    }
  }
export class MyArray {
  constructor() {
    this.length = 0;
    this.data = {};
  }
  
  unshift(item) {
    if (!item) { 
      return this.length;
    } else {
      for (let i = this.length; i > 0; i--) {
        this.data[i] = this.data[i - 1]
      }
    }
    this.data[0] = item;
    this.length++;
    return this.data;
  }
}```

Mi solucion…

unshift(item){
    // Tu código aquí 👈
    if (!item) return this.length;

    let currentEl = this.data[0];
    let nextEl = undefined;
    this.length++;

    for (let i = 1; i < this.length; i++) {
      nextEl = this.data[i]
      this.data[i] = currentEl;
      currentEl = nextEl;
    }
    this.data[0] = item
    console.log("unshift", this.data)
    return this.data;
  }
undefined