Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
Extend the given class

I'm trying to solve a javascript exercise working with objects and classes, I'm not very good with this and I don't know if I did it right, did I do it right?

1- Extend the given class so that it implements a count() function that prints to the console the number of elements contained in the "value" property (do not modify the given constructor)

instantiate the class and call the new function count()

//Do not modify this constructor.

function Clase(elem){
  this.valor = [];
  this.valor['elem1'] = 1;
  this.valor['elem2'] = 2;
  this.valor['elem3'] = 3;
  this.valor['elem4'] = elem;
}

my code =>

function Clase(elem){
  this.valor = [];
  this.valor['elem1'] = 1;
  this.valor['elem2'] = 2;
  this.valor['elem3'] = 3;
  this.valor['elem4'] = elem;
}

class Extendida extends Clase{
  contar(){
    const keys = Object.keys(this.valor)
    console.log(Object.keys(this.valor))
    const keyslen = keys.length
    return keyslen
  }
}

const objeto = new Extendida(4)
objeto.contar()
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your code's contar() method correctly returns the number of properties in clase.valor. clase.valor is an Array that is getting dynamic properties. Dynamic properties are not the same as Array elements, however.

For example:

let a = [];
a['x'] = 10;
console.log(a.length); // 0
console.log(Object.keys(a)); // ['x']
console.log(Object.keys(a).length); // 1

But if you could change Clase constructor, you could use class keyword for the base class. Also, instead of using an Array for clase.valor, you could use a Map:

class Clase {
    constructor(elem) {
        this.valor = new Map([
            ['elem1', 1],
            ['elem2', 2],
            ['elem3', 3],
            ['elem4', elem],
        ]);
    }

    // abstract
    contar() {
        return 0;
    }
}

Then Extendida:

class Extendida extends Clase {
    // override
    contar() {
        const keys = Array.from(this.valor.keys())
        console.log(keys)
        const keyslen = this.valor.size
        return keyslen
    }
}

So, in real code sometimes you use either plain objects (or records), Array, Map, Set etc., but Array with dynamic properties is a confusing programming pattern.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!