Instantly share code, notes, and snippets.

View 4.js
var formatDate = d=>`${d.getFullYear()}-${`${d.getMonth()+1}`.padStart(2,0)}-${`${d.getDate()}`.padStart(2,0)}`
var es=document.body.textContent.trim().split('\n').map(l => {let [,d,s]=l.split(/\[|\] /g); return {d: new Date(d), s}}).sort((a,b)=>a.d-b.d)
var xs=es.map(({d,s}) => { let m=d.getMinutes(); if (d.getHours()===23){d.setDate(d.getDate()+1);m=0;} return {date: formatDate(d), m,d,s}} )
var days=xs.reduce((o,{date,m,s})=>{const slots=o[date]&&o[date].slots||Array.from({length:60},()=>0); let g=s.match(/#\d+/); if (s.startsWith('falls')){for(let i=m;i<slots.length;i++)slots[i]=1} if (s.startsWith('wakes')){for(let i=m;i<slots.length;i++)slots[i]=0} return {...o,[date]:{...o[date],slots,...g&&{guard:g[0]}}} }, {})
var guards=Object.values(days).reduce((o, {slots,guard}) => {let name=guard.slice(1); const sleeptime=o[name]||0; return {...o,[name]:sleeptime+slots.reduce((a,b)=>a+b)};}, {})
var ds = Object.entries(days).filter(([date, o]) => o.guard==='#2593').map(([date, {slots}]) => slots)
Math.max(...ds.
@caub
caub / server.js
Last active Oct 15, 2018
https with letsencrypt
View server.js
// d run -d --name=ok -p 443:6100 -p 80:6000 --workdir=/home/node -v /etc/letsencrypt/:/etc/letsencrypt/:ro -v $PWD/server.js:/home/node/server.js node node server
var https = require("https");
var http = require("http");
var fs = require("fs");
var p="/etc/letsencrypt/live/ulti.pw/";
var hs=https.createServer({
key: fs.readFileSync(p+"privkey.pem")+"",
@caub
caub / promise-middleware.js
Created May 22, 2018
Don't use redux-saga
View promise-middleware.js
const promiseMiddleware = store => next => action => {
if (typeof action.then === 'function') {
return Promise.resolve(action).then(next);
} else if (action.value && typeof action.value.then === 'function') {
return Promise.resolve(action.value).then(value => next({ type: action.type, value }));
}
// else, not a promise
try {
return next(action);
} catch (e) {
View BetterMap.js
export default class BetterMap {
constructor(data) {
this.m = new Map(Array.isArray(data) || data instanceof Map ? data : Object.entries(data));
}
set(k, v) { // return BetterMap
this.m.set(k, v);
return new SortableMap(this.m);
}
delete(k) { // return BetterMap
this.m.delete(k, v);
View new unicode regex flags.js
// ## like \1 but named:
/(?<fruit>apple|fig)==\k<fruit>/u.test('fig==fig')
// true
// ## named group captures:
'we can'.replace(/(?<subject>\w+) (?<verb>\w+)/u, '$<subject>...$<verb>')
//"we...can"
'yes, we can'.replace(/(?<w>\w+)[,\s]+/gu, '$<w>...')
View downloadFromFs.js
const DIR = os.homedir() + '/.foo';
// adapted from https://stackoverflow.com/a/24977085/3183756
const downloadFromFs = (req, res) => {
const { name } = req.params;
const filePath = path.join(DIR, name);
fs.stat(filePath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
// 404 Error if file not found
View apollo.js
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
const TodoApp = ({ loading, error, data: { todos, refetch }, ...props }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<div {...props}>
<button onClick={() => refetch()}>Refresh</button>
<ul>{todos && todos.map(todo => <li key={todo.id}>{todo.text}</li>)}</ul>
@caub
caub / _output
Last active May 16, 2018
Dataloader knex benchmark
View _output
mapTo: 428.186ms
mapTo2: 319.058ms
ord: 348.390ms
mapToMany: 786.141ms
mapToMany2: 780.661ms
ord agg: 31856.442ms
View withData.js
import React from 'react';
/**
* Simple HOC, taking a fetcher function (returning a promise) then a Component
* @returns Component accepting a ({ data, error, loading }) => {..} function as children
*/
export default fetcher => Component =>
class extends React.PureComponent {
state = { loading: true, data: [], error: undefined };
View .light
#!/bin/bash
regexp='^[-+]?[0-9]*(\.[0-9]*)?$'
validateNumber() {
if [[ $1 == *[0-9]* && $1 =~ $regexp ]]; then
echo "$1"
else
printf >&2 '%s is not a valid number\n' "$1"
fi
}