Skip to content

Instantly share code, notes, and snippets.

/**
* @return example: '0zz12948ab0', length fixed
*/
function getRandomString(): string {
const rand = Math.random() * 2 ** 52;
const pad = '00000000000';
const padded = pad + rand.toString(36);
return padded.substr(padded.length - pad.length);
}
@jeiea
jeiea / useInterval.jsx
Created June 26, 2019 02:23
React hook version of useInterval
import { useEffect, useState } from 'react';
function useInterval(interval, setter) {
const [updater] = useState({});
updater.update = setter;
useEffect(() => {
const id = setInterval(() => {
updater.update(c => c + 1);
}, interval);
return () => clearInterval(id);
@jeiea
jeiea / HtmlToPlainText.kt
Created February 12, 2019 09:34
html to plain text kotlin port of https://stackoverflow.com/a/50363077
/**
* It depends on JSoup.
* Kotlin port of https://stackoverflow.com/a/50363077
*/
object Utils {
private val block = "address|article|aside|blockquote|canvas|dd|div|dl|dt|" +
"fieldset|figcaption|figure|footer|form|h\\d|header|hr|li|main|nav|" +
"noscript|ol|output|p|pre|section|table|tfoot|ul|video"
private val rxlongWSpaces = Regex("""\s{2,}""")
private val rxNestedBlock = Regex("""(\s*?</?(${block})[^>]*?>)+\s*""", RegexOption.IGNORE_CASE)
@jeiea
jeiea / diff-interface-typeclass.md
Last active February 1, 2019 10:36
Difference between OOP interfaces and FP type classes 번역

여러가지 관점에서 볼 수 있다. 공감받진 못하더라도, OOP의 인터페이스가 타입 클래스를 이해하는데 좋은 출발점이라고 생각한다 (당연히 아무것도 모르는 것보단 나을 것이다). 사람들은 개념적으로 타입 클래스가 타입을 집합처럼 구분한다고 말한다. "특정 연산과, 언어 자체로 표현할 수 없는 기대들을 만족하는 타입들의 집합"처럼 말이다. 이 말은 타당하고, "이 타입이 요구 조건을 만족하면 이 타입을 이 클래스의 인스턴스로 만들라"는 아무 메소드 없는 타입 클래스로 표현할 수 있다. 이건 인터페이스에서는 거의 볼 수 없는 활용이다.

구체적인 차이점을 말하자면, OOP 인터페이스보다 타입 클래스가 더 강력한 여러가지가 있다:

@jeiea
jeiea / 10.3-layout.md
Created December 27, 2018 04:45
하스켈 2010 레포트 들여쓰기 규칙을 필요에 의해 번역함

10.3 레이아웃(이하 들여쓰기)

2.7장에서 들여쓰기 규칙을 간단히 설명했습니다. 이번 장에서 더 자세히 정의합니다.

하스켈 프로그램의 의미는 들여쓰기에 따라 달라집니다. 중괄호와 세미콜론을 적절히 추가하는 것으로 들여쓰기의 효과를 완전히 갈음할 수 있습니다. 그렇게 한 프로그램은 들여쓰기할 필요가 없어집니다.

들여쓰기된 프로그램에 어떻게 중괄호와 세미콜론을 추가하는지 설명해서 들여쓰기의 효과를 설명하겠습니다. 들여쓰기 변환 함수 L을 정의하겠습니다. L의 입력은:

  • 아래 토큰이 추가된 하스켈 레포트 어휘 구문에 정의된 어휘소lexeme 스트림:
  • let, where, do, of 키워드 뒤에 {가 없으면 {n} 토큰이 그 키워드 뒤에 들어갑니다. n은 다음 어휘소의 들여쓰기 수준을 의미하고 파일의 끝일 때는 0이 됩니다.
@jeiea
jeiea / TsvReader.kt
Last active November 3, 2018 20:04
For those who file.readText().lines().map { it.split('\t') } is not sufficient
import java.io.Reader
/**
* Portable tsv reader supporting multiline
* Usage: File("a.tsv").bufferedReader().use { TsvReader(it).readAll() }
*/
class TsvReader(private val reader: Reader) {
private val sb = StringBuilder()
private val eof = (-1).toChar()
@jeiea
jeiea / FlatDictionary.cs
Last active September 1, 2018 10:35
A utility for importing separate xaml files while previewing it in xaml editor
using System;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Markup;
/// <summary>
/// A utility for importing separate xaml files while previewing it in xaml editor.
/// </summary>
// <example>
@jeiea
jeiea / WeakCache.cs
Created July 15, 2018 21:04
Not thread safe..
public class WeakCache<T> where T : class {
private Dictionary<object, WeakReference<T>> Index
= new Dictionary<object, WeakReference<T>>();
public bool TryGetValue(object key, out T val) {
if (Index.TryGetValue(key, out WeakReference<T> weak))
if (weak.TryGetTarget(out T target)) {
val = target;
return true;
}
@jeiea
jeiea / echo-server.js
Created March 25, 2018 09:54
node.js echo server
const net = require('net');
let clients = [];
let server = net.createServer(stream => {
stream.setEncoding('utf8');
clients.push(stream);
let idx = clients.indexOf(stream);
console.log(`client ${idx} connected.`);
stream.on('data', data => {
@jeiea
jeiea / 하스켈을 C만큼 빠르게 만들기 - 엄격함, 느긋함, 재귀 파헤치기.md
Last active February 9, 2018 01:26
Korean translation of 'Write Haskell as fast as C: exploiting strictness, laziness and recursion'

하스켈을 C만큼 빠르게 만들기: 엄격함, 느긋함, 재귀 파헤치기

원본: Write Haskell as fast as C: exploiting strictness, laziness and recursion

역주: 번역 시점에서 10년 된 글... 현재와는 다른 부분이 상당하다.

최근 메일링 리스트에서 Andrew Coppin이 긴 double 실수값 리스트의 평균을 계산하는 "깔끔하고 선언적인" 코드가 성능이 나쁘다고 불평했습니다.

import System.Environment

import Text.Printf