Skip to content

Instantly share code, notes, and snippets.

@jakubfiala
Created June 22, 2020 19:27
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 jakubfiala/185f7275ecf971c02bab5a70112c4c62 to your computer and use it in GitHub Desktop.
Save jakubfiala/185f7275ecf971c02bab5a70112c4c62 to your computer and use it in GitHub Desktop.
js functions that i need often and i am NOT making another npm package, fuck that
// like python's range, yields numbers from start to end (not inclusive)
export const range = function* (start, end, step = 1) {
let index = start;
while (index < end) {
yield index;
index++;
}
}
// like python's enumerate, yields [index, item]
export function* enumerate(iterable) {
let count = 0;
for (let item of iterable) {
yield [count++, item];
}
}
// returns a randomly selected item from a given array
export const choose = list => list[Math.floor(Math.random() * list.length)];
// converts degress to radians
export const rad = x => (x * Math.PI) / 180;
// converts radians to degrees
export const deg = x => (x * 180) / Math.PI;
// aint installing no lodash
// https://stackoverflow.com/a/27078401
export const throttle = (callback, wait) => {
let go = true;
return () => {
if (go) {
go = false;
setTimeout(() => {
go = true;
callback.call();
}, wait);
}
};
};
// returns the sum of numbers in the given array
export const sum = (vector) => {
let s = 0;
for (var i = 0; i < vector.length; i++) {
s += vector[i];
}
return s;
};
// returns the mean of numbers in the given array
export const mean = (vector) => {
return sum(vector) / vector.length;
};
// returns the variance of numbers in the given array
export const variance = (vectorMean, vector) => {
let s = 0;
for (let i = 0; i < vector.length; i++) {
s += (vector[i] - vectorMean) ** 2;
}
return s;
}
/**
* Standard deviation with N-1 normalisation factor
* which matches Matlab's `std` with the default `w` parameter
*
* @param {Array} vectorMean mean of the provided vector (provided separately for modularity)
* @param {Array} vector the vector itself
*/
export const stddev = (vectorMean, vector) => {
return Math.sqrt(variance(vectorMean, vector) / (vector.length - 1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment