Skip to content

Instantly share code, notes, and snippets.

View stekhn's full-sized avatar

Steffen Kühne stekhn

View GitHub Profile
@stekhn
stekhn / ConditionalWrapper.tsx
Last active June 10, 2022 09:00
React conditional wrapper that add an enclosing element based on a boolean condition
import * as React from 'react';
interface Props {
condition: boolean;
wrapper: Function;
children: React.ReactNode;
}
export const ConditionalWrapper: React.FC<Props> = ({ condition, wrapper, children }) => {
return condition ? wrapper(children) : children;
@stekhn
stekhn / ResponsiveWrapper.tsx
Created June 10, 2022 08:55
React responsive wrapper component that passes its current width and height to child elements. Supports default values and aspect ratios.
import React, { useRef, useLayoutEffect, useState } from 'react';
interface ResponsiveWrapperProps {
defaultWidth?: number;
defaultHeight?: number;
fixedWidth?: number;
fixedHeight?: number;
heightRatio?: number;
}
@stekhn
stekhn / useDimensions.tsx
Created June 10, 2022 08:49
React hook for responsive width and height with support for resize events
import { useState, useEffect } from 'react';
const getDimensions = () => {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
};
@stekhn
stekhn / useReducedMotion.tsx
Created June 10, 2022 07:55
React hook to disable animations for users which prefer reduced motion
import { useState, useEffect } from "react";
export function useReducedMotion() {
const [matches, setMatch] = useState(
window.matchMedia("(prefers-reduced-motion: reduce)").matches
);
useEffect(() => {
const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
const handleChange = () => {
@stekhn
stekhn / csv-to-json.js
Last active October 30, 2020 17:45
Converts a CSV string to JSON. Only works for well behaved CSV datasets without crazy string escaping or similar shenanigans.
function csvToJson(csv, columnSeparator = ',', rowSeparator = '\n') {
const inferType = (str) => {
if (!str) {
return;
} else if (!isNaN(str) || !isNaN(str.replace(',', '.'))) {
return parseFloat(str.replace(',', '.'));
} else if (Date.parse(str.replace(/"/g, ''))) {
return new Date(str.replace(/"/g, ''));
} else {
return str.replace(/"/g, '');
@stekhn
stekhn / date-range.js
Last active October 29, 2020 15:37
Create a range of dates between two dates. The step parameter defines the interval between the individual dates.
function dateRange(startDate, endDate, steps = 1) {
const dateArray = [];
let currentDate = new Date(startDate);
while (currentDate <= new Date(endDate)) {
dateArray.push(new Date(currentDate));
// Use UTC date to prevent problems with time zones and DST
currentDate.setUTCDate(currentDate.getUTCDate() + steps);
}
@stekhn
stekhn / sleep.js
Created July 29, 2020 12:53
Asynchronous sleep function for JavaScript, similar to Python. Also known as a wait or delay function
async function sleep(milliseconds) {
return new Promise(resolve => {
setTimeout(() => {
resolve(true);
}, milliseconds);
});
}
// await sleep(1000)
@stekhn
stekhn / confidence.js
Created April 27, 2020 18:01
Calculate the confidence interval (+) for a given confidence level (95 %) from an object array
function confidence(data, level = '95', key = 'value') {
const zValues = { '80': 1.28, '90': 1.645, '95': 1.96, '98': 2.33, '99': 2.58 };
const zValue = zValues[level];
const stdDevValue = stdDev(data, key);
return zValue * (stdDevValue / Math.sqrt(data.length))
}
function stdDev(data, key = 'value') {
const avg = data.reduce((sum, curr) => sum + curr[key], 0) / data.length;
@stekhn
stekhn / repro-number.js
Last active April 28, 2020 17:36
Calculate the the daily reproduction numbers (R) from an object array
function reproNumber(data, steps = 4, key = 'value') {
return data.map((obj, i) => {
const currentDays = data.slice(i - steps, i);
const previousDays = data.slice(i - steps * 2, i - steps);
const currentDaysSum = currentDays.reduce((sum, curr) => { return sum + curr[key]; }, 0);
const previousDaysSum = previousDays.reduce((sum, curr) => { return sum + curr[key]; }, 0);
return Object.assign({}, obj, {
r: currentDaysSum / previousDaysSum
});
@stekhn
stekhn / sma.js
Last active October 9, 2020 16:58
Calculate the simple moving average (SMA) from an object array
function sma(data, steps = 7, key = 'value') {
return data.map((obj, index) => {
const offset = index - Math.floor(steps / 2);
const window = data.slice(offset, steps + offset);
return Object.assign({}, obj, {
average: window.reduce((sum, curr) => {
return curr[key] ? sum + curr[key] : null;
}, 0) / window.length
});
}).filter(d => d.average);