Skip to content

Instantly share code, notes, and snippets.

View stekhn's full-sized avatar

Steffen Kühne stekhn

View GitHub Profile
@stekhn
stekhn / doubling-time.js
Created April 5, 2020 19:21
Calculates the doubling time, hence the time it takes for a certain value to double, assuming exponential growth.
function doublingTime(date1, value1, date2, value2) {
const diff = Math.ceil(date2.getTime() - date1.getTime()) / 86400000;
const days = Math.log(2) * diff / (Math.log(value2) - Math.log(value1));
return days;
}
// Usage:
// doublingTime(new Date('2020-04-01'), 300, new Date('2020-04-05'), 900);
// => 2.523719014285829
@stekhn
stekhn / json-to-csv.js
Last active October 30, 2020 15:37
Converts JSON to a CSV string. Only works with a one-dimensional JavaScript array of one-dimensional objects.
// Convert JSON to a CSV string
function jsonToCsv(json) {
const replaceEmpty = (key, value) => {
return value === null ? '' : value;
};
const parseRow = row => {
return header.map(fieldName =>
JSON.stringify(row[fieldName], replaceEmpty)
).join(',');
};
@stekhn
stekhn / post-to-slack.sh
Created March 2, 2020 12:21
Post to Slack using curl on the command line. The incoming webhook for your Slack team needs to be created beforehand.
# Read more about Slack webhooks here: https://api.slack.com/messaging/webhooks
curl -X POST \
-H 'Content-type: application/json; charset=utf-8' \
--data '{ "channel": "#mychannel", "username": "superbot", "icon_emoji": ":bot:", "text": "Foo" }' \
https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
@stekhn
stekhn / post-to-slack.js
Last active July 18, 2022 15:07
Use webhooks for posting to Slack. Works great with Google Cloud Functions and Google Cloud Scheduler. The incoming webhook for your Slack team needs to be created beforehand.
const https = require('https');
exports.postToSlack = () => {
// Read more about Slack webhooks here: https://api.slack.com/messaging/webhooks
const webhookPath = '/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
const payload = {
'channel': '#mychannel',
'username': 'slackbot',
@stekhn
stekhn / parse-csv.js
Last active March 2, 2020 13:48
Converts a CSV string to JSON. Assumes valid and well-formed CSV with a header. Only works for the most simple use cases.
// Convert CSV string to JavaScript object array
const parseCSV = (string) => {
const removeEmpty = (string) => string.length > 0;
const removeQuotes = (string) => string.length > 0 ? string.replace(/^["'](.*)["']$/, '$1') : undefined;
const lines = string.split(/\r?\n/).filter(removeEmpty);
const rows = lines.map(line => line.split(/,|;/).map(removeQuotes));
return rows.reduce((accArr, currRow, rowIndex) => {
if (rowIndex != 0) {
@stekhn
stekhn / remove-node-modules.sh
Created November 28, 2019 15:51
Remove all node_modules folders in a directory recursively
find . -name "node_modules" -type d -prune -exec rm -rf '{}' +
@stekhn
stekhn / hareNiemeyer.js
Last active April 23, 2020 13:12
Simple implementation of the Hare-Niemeyer (or Hamilton or largest remainder) method for allocating parliament seats proportionally
const results = [
{ party: 'socialists', votes: 130755 },
{ party: 'conservatives', votes: 102068 },
{ party: 'liberals', votes: 34012 },
{ party: 'greens', votes: 31090 },
{ party: 'crazypeople', votes: 11111 }
];
const hareNiemeyer = (results, seats) => {
@stekhn
stekhn / quantize.js
Last active January 7, 2020 20:34
Map a continuous value within a certain domain to a discrete value in JavaScript. Great for maps where you need to find a certain color for a given value.
const quantizeScale = (arr, min, max) => {
const steps = colors.length;
const increment = (max - min) / steps;
const bins = Array.apply(undefined, Array(steps)).map((bin, index) => (index * increment) + min);
return value => {
for (let i = 0; i < bins.length; i++) {
if (value <= bins[i]) {
return colors[i];
@stekhn
stekhn / gist:0222f055db2eddd9cd93d006e859a759
Created August 9, 2018 09:48
Fix several problems with PDFs just by rewriting them with Ghostscript
gs \
-o fixed.pdf \
-sDEVICE=pdfwrite \
-dPDFSETTINGS=/prepress \
broke.pdf
@stekhn
stekhn / writeConcurrent.js
Created August 6, 2018 15:47
Concurrently write one JSON file from multiple processes spawned by the Node.js "cluster" module. Uses a lockfile to prevent hickups.
const fs = require('fs');
const os = require('os');
const path = require('path');
const cluster = require('cluster');
const lockFile = require('lockfile');
const filePath = path.resolve(__dirname, 'result.json');
const lockPath = path.resolve(__dirname, 'result.json.lock');