Skip to content

Instantly share code, notes, and snippets.

@tokland
tokland / game.js
Last active June 13, 2020 10:22 — forked from andreuestanyalonso/game.js
Simple Canvas game loop with key events
const canvas = document.getElementById("tutorial");
const context = canvas.getContext("2d");
function drawBackground() {
context.beginPath();
context.fillStyle = "rgb(200, 200, 200)";
context.rect(0, 0, 640, 480);
context.fill();
context.closePath();
}
@tokland
tokland / tuples.ts
Last active February 17, 2020 20:43 — forked from willfrew/tuples.ts
Fun with tuple types in Typescript 3.0
type Length<T extends any[]> = T["length"];
type Head<T extends any[]> = T[0];
type Tail<T extends any[]> = ((...xs: T) => any) extends (x: any, ...t: infer T) => any ? T : never;
type Last<T extends any[]> = {
0: never;
1: T[0];
">1": Last<Tail<T>>;
}[Length<T> extends 0 ? 0 : Length<T> extends 1 ? 1 : ">1"];
@tokland
tokland / fetch_kindle.js
Last active April 14, 2020 17:33 — forked from yangchenyun/fetch_kindle.js
Get back my books from Kindle
#!/usr/bin/env node
/*
* @fileoverview Program to free the content in kindle books as plain HTML.
*
* This is largely based on reverse engineering kindle cloud app
* (https://read.amazon.com) to read book data from webSQL.
*
* Access to kindle library is required to download this book.
*/
@tokland
tokland / promise_map.js
Last active March 1, 2022 00:18 — forked from anvk/promises_reduce.js
Execute promises sequentially (one at at a time) and return array with the results
function promiseMap(inputValues, mapper) {
const reducer = (acc$, inputValue) =>
acc$.then(acc => mapper(inputValue).then(result => acc.push(result) && acc));
return inputValues.reduce(reducer, Promise.resolve([]));
}
/* Example */
const axios = require('axios');
@tokland
tokland / importer.rb
Last active December 20, 2015 20:59 — forked from regedarek/importer.rb
class Importer
CODES = {:header, "00F", :data => "00I"}
def self.import_products(fileobj)
fileobj.lines.each_slice(4).map do |group_lines|
type, *data_lines = group_lines.map(&:strip)
case type
when CODES[:header]
# what to do/return here?
when CODES[:data]
# Usage:
# $loopc 3 echo 'hello world'
# hello world
# hello world
# hello world
#
function loopc {
LIMIT=$1
shift 1
@tokland
tokland / external-command.rb
Created August 18, 2010 18:01 — forked from careo/external-command.rb
Capture stderr data on EventMachine.popen
require 'rubygems'
require 'eventmachine'
$stdout.sync = true
$stderr.sync = true
EM.run {
EM.add_periodic_timer(0.1) {
$stdout.write "stdout\n"