Skip to content

Instantly share code, notes, and snippets.

@Rycochet
Rycochet / Math.range
Created January 24, 2014 13:39
Make sure a number is within a minimum and maximum
/**
* Make sure a number is within a minimum and maximum
* @param {number} min
* @param {number} num
* @param {number} max
* @returns {number}
*/
Math.range = function(min, num, max) {
return Math.max(min, Math.min(num, max));
};
@Rycochet
Rycochet / String.prototype.regex
Last active January 4, 2016 08:48
Split a string into an array of regex matches, or a single result if only a single match
/**
* Split a string into an array of regex matches, or a single result if only a single match
* @param {RegExp} r The pattern to check against
* @return {Array|string|number} The matches
*/
String.prototype.regex = function(r) {
var a = this.match(r), i, rx;
if (a) {
if (r.global) {
if (/(^|[^\\]|[^\\](\\\\)*)\([^?]/.test(r.source)) { // Try to match "(blah" but not "\(blah" or "(?:blah" - ignore invalid regexp
@Rycochet
Rycochet / rgba()
Last active January 24, 2018 14:32
Javascript hex to rgb()/rgba()
// Please note this uses my Math.range and String.regex methods
/**
* Convert a hex colour to a rgb/rgba value
* @param {string} hex
* @param {?number} opacity
* @returns {string}
*/
function rgba(hex, opacity) {
var colours = hex.regex(/#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})/i).map(function(val) {
return Math.range(0, parseInt(val, 16), 255);