Created
February 22, 2018 19:30
-
-
Save andrejewski/25be684abca3b9f607b65f1e9a979732 to your computer and use it in GitHub Desktop.
A small refactor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // A quick refactor | |
| // 1 | |
| function foo (fieldValue) { | |
| //If the fieldValue is a number, use ID | |
| //Otherwise, use codeName | |
| //Postgres gets grouchy about comparing strings to numbers | |
| let fieldName; | |
| try { | |
| const parsed = parseInt(fieldValue); | |
| if(isNaN(parsed)) { | |
| fieldName = 'codeName'; | |
| } else { | |
| fieldName = 'id'; | |
| } | |
| } catch(e) { | |
| //Nothing to worry about | |
| fieldName = 'codeName'; | |
| } | |
| } | |
| // 2: separate type checking and behavior | |
| function isNumber (value) { | |
| try { | |
| const parsed = parseInt(fieldValue); | |
| return !isNaN(parsed); | |
| } catch (error) {} | |
| return false; | |
| } | |
| function foo (fieldValue) { | |
| const fieldName = isNumber(fieldValue) ? 'id' : 'codeName'; | |
| } | |
| // 3: parseInt() never throws | |
| function foo (fieldValue) { | |
| const isNumber = !isNaN(parseInt(fieldValue)); | |
| const fieldName = isNumber ? 'id' : 'codeName'; | |
| } | |
| // 4: always provide a radix to parseInt() | |
| function foo (fieldValue) { | |
| const isNumber = !isNaN(parseInt(fieldValue, 10)); | |
| const fieldName = isNumber ? 'id' : 'codeName'; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.