1

Is there a better way to do this?

if(cpf.length !== 11 || cpf === "00000000000" || cpf === "11111111111" ||
        cpf === "22222222222" || cpf === "33333333333" || cpf === "44444444444" ||
        cpf === "55555555555" || cpf === "66666666666" || cpf === "77777777777" ||
        cpf === "88888888888" || cpf === "99999999999"){
1
  • Technically this is more of a "code review" than an issue. Commented Apr 18, 2017 at 13:52

3 Answers 3

3

You could debate if this is better but this is what I like to do in that sort of situation:

// Name this something relevant to the problem
var possibleValues = ["0000000000", ...];
if (possibleValues.includes(cpf)) {
  // do stuff
}

or if you're in an environment that doesn't have includes

if (possibleValues.indexOf(cpf) > -1) {
  // do stuff
}

Another possibility is using a regular expression:

if (cpf.length === 11 && cpf.match(/^(\d)\1+$/)) {
  // do stuff
}
  • ^: Start at the beginning
  • (\d): Look for a digit and remember it
  • \1+: Look for the remembered digit repeatedly
  • $: Hit the end of the string
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! Sometimes i get 'tunnel vision' when working improvements for things like this. Also is there any performance gain/loss on the solutions above?. I loved the RegEx solution btw!
@VictorMedeiros Glad I could help! Technically, all of these solutions are likely slower than a bunch of ||s. However, it's likely a difference of 1ms or less and unless you really need to squeeze out that last little drop, it's not worth the effort and cruft to optimize it. Always make sure it works and works fast enough before optimizing.
to be precise, this part shouldn't be \1{10} rather than \1+, Edit: wait something's wrong here his first condition is cpf.length !== 11 so this whole thing should be if (cpf.length !== 11 || cpf.test(/^(\d)\1{10}$/)) { ... }
sry, realized too late that I have a mistake in my edit: it's regex.test(value) or string.match(regex) so ... if (cpf.length !== 11 || cpf.match(/^(\d)\1{10}$/)) { ... }
2

Using indexOf Something like

var possibleValues = [ "00000000000", "1111111111" ]; //add more values

if ( cpf.length != 11 || possibleValues.indexOf( cpf ) != -1 )
{
  //value matching
}

Comments

0

Alternative Ecmascript5 solution using isNaN() and RegExp.text() functions:

if (cpf.length !== 11 || (!isNaN(f = cpf[0]) && new RegExp("^"+ f + "{11}$").test(cpf))) {
    // do something
}

isNaN() - to check if we have only numbers(at start)

new RegExp("^"+ f + "{11}$").test(cpf) - to test if we have a sequence of same 11 digits

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.