How do I create instance of a constructor class in Javascript?

Viewed 113

I was trying to create an instance of a constructor function if one of the array elements created from the instance of the constructor does not have the same email.

let users = [];
class User{
    constructor(email, name, age, lang){
         this.email = email;
         this.name = name;
         this.age = age;
         this.lang = lang
    }
    save(){
        users.push(this)
    }
}

function validate(email, name, age, lang){
    let uEmail = email;
    users.forEach(ele =>{
        if(ele.email == email){
            console.log('You have account with us')
        }else if(!ele.email){
          creatObj(uEmail, name, age, lang)
        }
     })

 }
function creatObj(email,name, age, lang){
    new User('s@s.com',name, age, lang).save()
}

when I ran the code with the same email I need the not to push that instance to the users array. unfortunately it keeps pushing the instance even if the condition is not met. I was expecting the users array to contain elements if they have unique email

Can anyone help?

1 Answers

It would be best to use a lookup by a key (e.g. lower-case email address). And use a proper data structure (e.g. Object, Map, Set) to ensure you do not have to search the whole array.

A minimally modified version of your code:

const usersByEmail = {};
class User{
    constructor(email, name, age, lang){
         this.email = email;
         this.name = name;
         this.age = age;
         this.lang = lang
    }
    save(){
        usersByEmail[this.email.toLowerCase()] = this;
    }
}

function getOrCreateUser(email, name, age, lang){
    if (email.toLowerCase() in usersByEmail) {
        console.log('You have account with us');
    } else {
        new User(email ,name, age, lang).save();
    }
    return usersByEmail[email.toLowerCase()];
}

getOrCreateUser('s@s.com', 'sam', 32, 'en');
getOrCreateUser('s@s.com', 'samuel', 23, 'es');
getOrCreateUser('a@b.com', 'other guy', 44, 'en');
getOrCreateUser('s@s.com', 'sam', 32, 'en');

console.warn('as object...');
console.log(usersByEmail);

console.warn('as array...');
console.log(Object.values(usersByEmail));

Related