Skip to content

Instantly share code, notes, and snippets.

View IceCreamYou's full-sized avatar

Isaac Sukin IceCreamYou

View GitHub Profile
@IceCreamYou
IceCreamYou / uuid.js
Created November 17, 2015 09:07
Quickly returns a random UUID in JavaScript that is compliant with RFC-4122 Version 4.
/**
* Quickly returns a random UUID that is compliant with RFC-4122 Version 4.
*
* An example result is "2c3fa383-0d9d-4104-8fa2-58fdf614f021"
*
* Works in modern browsers and IE11+, and not Android Browser. A fallback if
* you care about those is to drop the Uint32Array and crypto lines, and
* replace the dX = buf[X] lines with dX = Math.random() * 0x100000000 >>> 0.
* In node.js do the same but use dX = crypto.randomBytes(4).readUInt32BE(0).
*
@IceCreamYou
IceCreamYou / rsquared3.js
Created September 5, 2015 21:42
Indicates the linear correlation of a three-dimensional data set.
/**
* Returns the r^2 value for a three-dimensional data set.
*
* `r` is the Pearson product-moment correlation coefficient, a measure of
* linear correlation.
*
* @param {Object[]} data
* An array of vectors with `x`, `y`, and `z` properties representing points
* in the data set.
*
/**
* Classify a numeric input.
*
* @param {Number} value
* The number to classify.
* @param {Object/Number[]} [buckets=[-2, -2/3, 2/3, 2]]
* An object or numeric array used to classify `value`. If `buckets` is an
* array, the returned category will be the first of "very low," "low,"
* "medium," and "high," in that order, where the correspondingly ordered
* bucket value is higher than the `value` being classified, or "very high"
@IceCreamYou
IceCreamYou / percentile.js
Last active November 17, 2022 01:54
Utility functions to calculate percentiles and percent ranks in a JavaScript array.
// Returns the value at a given percentile in a sorted numeric array.
// "Linear interpolation between closest ranks" method
function percentile(arr, p) {
if (arr.length === 0) return 0;
if (typeof p !== 'number') throw new TypeError('p must be a number');
if (p <= 0) return arr[0];
if (p >= 1) return arr[arr.length - 1];
var index = (arr.length - 1) * p,
lower = Math.floor(index),
@IceCreamYou
IceCreamYou / getMouseCoords.js
Created June 20, 2015 23:21
Gets the coordinates of the mouse relative to a container.
var container = document.getElementById('container'), // Pick the element(s) you care about
halfBoxSize = 0, // Facilitates placing boxes (click in the middle, get the upper-left coords)
roundPxToNearest = 5, // Snap to grid
roundPctToNearest = 0.0000001; // Precision for percentage values
container.addEventListener('click', reportLocation, false); // mousemove is another useful event
function reportLocation(event) {
var floorCoords = this.getBoundingClientRect(),
leftPx = roundPxToNearest * Math.round((event.clientX - floorCoords.left - halfBoxSize) / roundPxToNearest),
topPx = roundPxToNearest * Math.round((event.clientY - floorCoords.top - halfBoxSize) / roundPxToNearest),
@IceCreamYou
IceCreamYou / updateQueryParam.js
Created June 20, 2015 03:33
Updates a URL query parameter (or adds it if it doesn't already exist). Useful with history.pushState() / history.replaceState().
/**
* Create or update the value of a URL query parameter.
*
* Given an input URL, a query parameter, and a value, if the query parameter
* already exists in the URL, this function replaces that paramter's value with
* the given value; otherwise, this function adds the parameter to the URL and
* sets it to the given value. Returns the modified URL.
*/
function updateQueryParam(url, param, value) {
var search = new RegExp('([?&])(' + param + ')=[^&]*|$', 'i');
/**
* Returns a normally distributed random variable.
*
* Adapted from http://blog.yjl.im/2010/09/simulating-normal-random-variable-using.html
* To the extent I have the ability to do so, this code is released into the public domain.
*/
function random_normal(mean, variance) {
if (typeof mean === 'undefined') {
mean = 0.0;
}

Keybase proof

I hereby claim:

  • I am IceCreamYou on github.
  • I am icecreamyou (https://keybase.io/icecreamyou) on keybase.
  • I have a public key whose fingerprint is 003D 9415 45F6 8791 898B 82BE 2F57 FE00 41D6 AF70

To claim this, I am signing this object:

@IceCreamYou
IceCreamYou / bucketNumbers.js
Last active October 28, 2020 16:36
Put numbers into buckets either by bucket size or range size.
/**
* Utility method to round numbers to a given number of decimal places.
*
* Usage:
* 3.5.round(0) // 4
* Math.random().round(4) // 0.8179
* var a = 5532; a.round(-2) // 5500
* Number.prototype.round(12345.6, -1) // 12350
* 32..round(-1) // 30 (two dots required since the first one is a decimal)
*/
@IceCreamYou
IceCreamYou / textFromComment.js
Created April 27, 2014 05:29
A utility function to extract convenient multi-line strings with embedded variables from comments in function bodies. Particularly useful for inline GLSL shader code.
/**
* Extract a multiline string from a multiline comment inside a function.
*
* @param {Function} fn The function containing the string.
* @param {vars} A map of tokens to values to replace in the string.
*/
function textFromComment(fn, vars) {
var s = (fn + '').match(/^[\s\S]*?\/\*!?\s*([\s\S]+?)\s*\*\/$/m)[1];
if (typeof vars !== 'undefined') {
var keys = Object.keys(vars).sort(function(a, b) { return b.length - a.length; });