Created
July 1, 2021 16:10
-
-
Save kuuote/d63f6d45de1f9b43507782d22c137e58 to your computer and use it in GitHub Desktop.
lolcat imitation for deno
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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