How do you test if a js objects property as ONLY lowercase letters using a regular expression?

60 Views Asked by At

Heres my class:

class Cipher(){     
    constructor(key) {
        this.key = !key ? String.fromCharCode(...Array.from({ length: 100 }, () => Math.floor(Math.random() * 26 + 97)),): key;
        if (this.key === '' || this.key.match(/[a-z]/g) !== this.key) {
            throw new Error('Bad key');
        }
     }
   }

Basically I want:

const foo = new Cipher();
console.log(foo.key);
// random 100 character string
const foo = new Cipher("bar");
console.log(foo.key);
// bar
const foo = new Cipher("Bar")
// [Error 'Bad key']

but every test I've put where 'new Cipher()' is called (an instance with no argument parsed) the code throws an error, basically I want it to recognize that I've already made a random key of 100 lowercase letters and to use that instead...

1

There are 1 best solutions below

0
On

I think your question is:

I want to produce a 100-letter string of random letters for key when my constructor is called with no argument, but to use the given key if there is one. But I want to require that the key only have lowercase letters in it.

If so:

constructor(key) {
    if (key) {
        if (/[^a-z]/.test(key)) {     // true if any character in key isn't a-z
           throw new Error('Bad key');
        }
        this.key = key;
    } else {
        this.key = String.fromCharCode(
            ...Array.from({ length: 100 }, () => Math.floor(Math.random() * 26 + 97))
        );
    }
}

Live Example:

class Example {
    constructor(key) {
        if (key) {
            if (/[^a-z]/.test(key)) {     // true if any character in key isn't a-z
               throw new Error('Bad key');
            }
            this.key = key;
        } else {
            this.key = String.fromCharCode(
                ...Array.from({ length: 100 }, () => Math.floor(Math.random() * 26 + 97))
            );
        }
    }
}
console.log('new Example():');
console.log(new Example().key);
console.log('new Example("foo"):');
console.log(new Example("foo").key);
console.log('new Example("Bad"):');
console.log(new Example("Bad").key);