Skip to content

Instantly share code, notes, and snippets.

@andrejewski
Created February 22, 2018 19:30
Show Gist options
  • Select an option

  • Save andrejewski/25be684abca3b9f607b65f1e9a979732 to your computer and use it in GitHub Desktop.

Select an option

Save andrejewski/25be684abca3b9f607b65f1e9a979732 to your computer and use it in GitHub Desktop.
A small refactor
// 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';
}
@BigAB
Copy link
Copy Markdown

BigAB commented Feb 23, 2018

// 5? : use parseFloat so you don't have to worry about radix and an arrow function to make it a sweet one-liner
const foo = fieldValue => isNaN(parseFloat(fieldValue)) ? 'codeName' : 'id'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment