Skip to content

Instantly share code, notes, and snippets.

@t-davies
t-davies / js-yaml-ruby-types.js
Last active November 18, 2020 10:33
Parses a YAML file with unknown !ruby tags, using js-yaml
import { Type, Schema } from "js-yaml";
const BigDecimal = new Type("!ruby/object:BigDecimal", {
kind: "scalar",
construct: (data) => {
return parseFloat(data.split(":")[1]);
},
});
const supportedTags = [BigDecimal];
@t-davies
t-davies / cli-oauth.ts
Last active November 18, 2020 10:34
Slightly messy reference for implementing client-side OAuth 2 flow in a CLI app
// quick and dirty reference for oauth flow in CLI apps
let server: http.Server;
const recievedCode = new Promise<string>((resolve, reject) => {
server = http.createServer((req, res) => {
const { pathname, searchParams } = new URL(
req.url,
"http://localhost:3000/"
);
@t-davies
t-davies / optimal-ec2-single-core.js
Created August 30, 2020 14:57
Suggests optimal EC2 instance mix for single-core apps, like CS:GO servers
const hosts = [
{
name: "z1d.12xlarge",
capacity: 48,
cost: 5.273,
},
{
name: "z1d.6xlarge",
capacity: 24,
cost: 2.636,
@t-davies
t-davies / watch-if.sh
Last active April 21, 2020 12:09
Watches a *nix network interface for status changes
#! /bin/bash
watch_for_interface()
{
if (ifconfig "$1" | grep -q "status: active")
then
echo "[$1] state changed: active"
echo "...do stuff here..."
else
echo "[$1] state changed: inactive"
fi
@t-davies
t-davies / word-count-kata.js
Last active February 18, 2019 16:54
JavaScript word count, 5 mins kata
// task: count frequency of words in a string
// assumptions:
// - "words" are separated by spaces
// - input will always be a string, never undefined/null etc.
// - numbers and emoji are "words"
// - input will be latin script
// steps:
// - split input by ' '
AWS.config.update({
httpOptions: {
agent: process.env.HTTPS_PROXY
? require('proxy-agent')(process.env.HTTPS_PROXY)
: undefined,
},
});
export function getNestedValue(key, object) {
return key.split('.').reduce((previous, current) => {
return previous[current];
}, object);
}
export function setNestedValue(key, value, object) {
const compound = key.split('.');
return compound.reduce((previous, current, index) => {
if (index === compound.length - 1) {
@t-davies
t-davies / debounce.js
Last active July 13, 2018 14:01
Debounce with arguments support
/* @flow */
export function debounce(callback: () => mixed, timeout: number) {
let activeTimeout;
return function() {
if (activeTimeout) {
clearTimeout(activeTimeout);
}
@t-davies
t-davies / fs-cache.js
Created May 21, 2018 14:09
Node.js: cache file and directory reads by wrapping `fs`
import fs from "fs";
import moment from "moment";
const cache = new Map();
function put(key, data) {
cache.set(key.toLowerCase(), {
expires: moment.utc().add(moment.duration(1, "h")),
value: data
});