Skip to content

Instantly share code, notes, and snippets.

@heaversm
Last active August 30, 2020 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heaversm/29f5fb34c32ca5d4e67640f055ce8c08 to your computer and use it in GitHub Desktop.
Save heaversm/29f5fb34c32ca5d4e67640f055ce8c08 to your computer and use it in GitHub Desktop.
Common JS Utility Functions
//MAP A NUMBER FROM ONE RANGE TO ANOTHER:
function map_range(value, low1, high1, low2, high2) {
return low2 + (high2 - low2) * (value - low1) / (high1 - low1);
}
//RANDOM DECIMAL NUMBER BETWEEN [MIN] and [MAX]:
randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
//GET A RANDOM INTEGER BETWEEN [MIN] and [MAX]:
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
//CONVERT ANY STRING TO SLUG
function slugify(str){
return str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('_');
}
//TITLE CASE STRING
function titleCase(str) { return str.toLowerCase().replace(/(^|\s)\S/g, (firstLetter) => firstLetter.toUpperCase());}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment