Skip to content

Instantly share code, notes, and snippets.

View jooyunghan's full-sized avatar

Jooyung Han jooyunghan

View GitHub Profile
@jooyunghan
jooyunghan / even.js
Created January 12, 2018 13:24
상호재귀 stackoverflow even/odd
function even(n) {
if (n === 0) return true;
else return odd(n-1);
}
function odd(n) {
if (n === 0) return false;
else return even(n-1);
}
console.log(even(100000));
@jooyunghan
jooyunghan / rd.js
Created January 12, 2018 13:13
RD Parser for Parens (showing stack oveflow)
const FAIL = {};
let _pos;
let _input;
function parse(input) {
_input = input;
_pos = 0;
const r = parens();
if (r === FAIL || _pos !== _input.length) throw new Error('parse error');
return r;
@jooyunghan
jooyunghan / matcher.js
Last active January 9, 2018 12:17
Parser using JSGenerators
// parser = string -> [match, remainder]
// read single item
function* item(s) {
if (s.length > 0) yield [s[0], s.slice(1)];
}
function run(p, s) {
return [...p(s)]
}
const letters = c => ({
0: " ",
1: "",
2: "abc",
3: "def",
4: "ghi",
5: "jkl",
6: "mno",
7: "pqrs",
8: "tuv",
@jooyunghan
jooyunghan / phonenumber.js
Last active January 9, 2018 06:54
flatMap/map for JS Iterable(eg. Array, String)
const flatMap = (f, as) => {
const result = [];
for (const a of as) {
result.push(...f(a));
}
return result;
}
const map = (f, as) => {
const result = [];
@jooyunghan
jooyunghan / phonenumber.js
Last active January 9, 2018 06:53
traverse/sequence for JSArray
const traverse = (f, as) => sequence(map(f, as));
const sequence = (as) => {
if (as.length === 0) return [""];
return flatMap(a => map(b => [a, ...b], sequence(as.slice(1))), as[0])
}
var letterCombinations = function(digits) {
if (digits.length === 0) return [];
const result = [''];
const letters = ' ||abc|def|ghi|jkl|mno|pqrs|tuv|wxyz'.split('|');
for (const d of digits) {
for (const r of result.splice(0)) {
for (const l of letters[+d]) {
result.push(r + l);
}
@jooyunghan
jooyunghan / gen-async.js
Last active December 22, 2017 13:51
AsyncIterator for Observable Using Ag() coroutine
function createAsyncIterator() {
const self = this;
return ag(function*() {
const resume = [];
const values = [];
const subscription = self.materialize().subscribe(value => {
values.push(value);
resume.splice(0).forEach(r => r());
});
@jooyunghan
jooyunghan / ag.js
Last active December 22, 2017 01:37
Async Generator Wrapper. Can be used with normal generator functions
export function ag(f) {
const promises = [];
const g = f();
return {
[Symbol.asyncIterator]() {
return this;
},
next(input) {
if (promises.length > 0) {
return new Promise((resolve, reject) => {
async function* createAsyncIterator() {
const promise = [];
const values = [];
const subscription = this.materialize().subscribe(value => {
values.push(value);
promise.splice(0).forEach(r => r());
});
try {