2

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('[email protected]',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
  • 3
    How/where do you use the validate function? Commented May 27, 2020 at 6:31

1 Answer 1

2

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('[email protected]', 'sam', 32, 'en');
getOrCreateUser('[email protected]', 'samuel', 23, 'es');
getOrCreateUser('[email protected]', 'other guy', 44, 'en');
getOrCreateUser('[email protected]', 'sam', 32, 'en');

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.