Skip to main content
added 352 characters in body
Source Link
janos
  • 113.1k
  • 15
  • 154
  • 396

Instead of this loop:

for i := 48; i <= 57; i++ {
    if int(r) == i {
        return (int(r) - 48), nil
    }
}

This is equivalent:

intval := int(r)
if 48 <= intval && intval <= 57 {
    return (intval - 48), nil
}

And if we subtract 48 earlier, the code will start to look more natural:

intval := int(r) - 48
if 0 <= intval && intval <= 9 {
    return intval, nil
}

And what is this magical 48 really? The ASCII code of '0' of course! We can write it that way:

intval := int(r) - '0'

The name ParseNum is a bit misleading. For example a function called parseInt usually tries to convert a string to an integer, and if the string is not a valid integer, it raises an error. That's not how ParseNum works. ParseNum will happily convert "he1l2l3oth4ere" to [1234]. A better name would be StripNonDigit or ExtractDigits.

Instead of this loop:

for i := 48; i <= 57; i++ {
    if int(r) == i {
        return (int(r) - 48), nil
    }
}

This is equivalent:

intval := int(r)
if 48 <= intval && intval <= 57 {
    return (intval - 48), nil
}

And if we subtract 48 earlier, the code will start to look more natural:

intval := int(r) - 48
if 0 <= intval && intval <= 9 {
    return intval, nil
}

And what is this magical 48 really? The ASCII code of '0' of course! We can write it that way:

intval := int(r) - '0'

Instead of this loop:

for i := 48; i <= 57; i++ {
    if int(r) == i {
        return (int(r) - 48), nil
    }
}

This is equivalent:

intval := int(r)
if 48 <= intval && intval <= 57 {
    return (intval - 48), nil
}

And if we subtract 48 earlier, the code will start to look more natural:

intval := int(r) - 48
if 0 <= intval && intval <= 9 {
    return intval, nil
}

And what is this magical 48 really? The ASCII code of '0' of course! We can write it that way:

intval := int(r) - '0'

The name ParseNum is a bit misleading. For example a function called parseInt usually tries to convert a string to an integer, and if the string is not a valid integer, it raises an error. That's not how ParseNum works. ParseNum will happily convert "he1l2l3oth4ere" to [1234]. A better name would be StripNonDigit or ExtractDigits.

Source Link
janos
  • 113.1k
  • 15
  • 154
  • 396

Instead of this loop:

for i := 48; i <= 57; i++ {
    if int(r) == i {
        return (int(r) - 48), nil
    }
}

This is equivalent:

intval := int(r)
if 48 <= intval && intval <= 57 {
    return (intval - 48), nil
}

And if we subtract 48 earlier, the code will start to look more natural:

intval := int(r) - 48
if 0 <= intval && intval <= 9 {
    return intval, nil
}

And what is this magical 48 really? The ASCII code of '0' of course! We can write it that way:

intval := int(r) - '0'