Skip to content

Instantly share code, notes, and snippets.

@kuuote
Created July 1, 2021 16:10
Show Gist options
  • Save kuuote/d63f6d45de1f9b43507782d22c137e58 to your computer and use it in GitHub Desktop.
Save kuuote/d63f6d45de1f9b43507782d22c137e58 to your computer and use it in GitHub Desktop.
lolcat imitation for deno
import { BufReader } from "https://deno.land/[email protected]/io/bufio.ts";
const stdin = BufReader.create(Deno.stdin);
const decoder = new TextDecoder("utf-8", {fatal: true});
const encoder = new TextEncoder();
const colors = [
[128, 255, 128],
[128, 128, 255],
[128, 255, 255],
[255, 128, 128],
[255, 255, 128],
[255, 128, 255],
].map(([r, g, b]) => encoder.encode(`\x1b[38;2;${r};${g};${b}m`));
let cnt = 0;
let b: Uint8Array | null;
let buf: number[] = []; // 通常文字のバッファ(マルチバイトをちゃんと処理するため)
while ((b = await stdin.peek(1)) !== null) {
await stdin.readByte();
if (b[0] === 0x1b) {
const buf = [0x1b];
while (await stdin.peek(1) !== null) {
const b = (await stdin.readByte())!;
buf.push(b);
if ((0x41 <= b && b <= 0x5a) || (0x61 <= b && b <= 0x7a)) {
await Deno.stdout.write(Uint8Array.from(buf));
break;
}
}
} else {
await Deno.stdout.write(colors[cnt++ % colors.length]);
buf.push(b[0]);
try {
const arr = Uint8Array.from(buf);
decoder.decode(arr);
await Deno.stdout.write(arr);
buf = [];
} catch {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment