Skip to content

Instantly share code, notes, and snippets.

@Voronar
Last active May 31, 2022 17:56
Show Gist options
  • Save Voronar/b614d41040d4a4697202ae3843dda094 to your computer and use it in GitHub Desktop.
Save Voronar/b614d41040d4a4697202ae3843dda094 to your computer and use it in GitHub Desktop.
Java scripts
const gen_map = (f, g) => function* (arg) {
for (const x of g(arg))
yield f(x)
};
const gen_filter = (f, g) => function* (arg) {
for (const x of g(arg))
if (f(x))
yield x
};
const add_one = (x) =>
x + 1
const isEven = (x) =>
(x & 1) === 0
const range = function* (y = 1) {
let x = 0;
while (x < y)
yield x++
}
const N = 10_000_000;
console.time("gen");
for (
const x of gen_map(add_one, gen_filter(isEven, range))(N)
) {
// console.log('gen evens incr', x)
}
console.timeEnd("gen");
console.time("arr");
const arr = Array(N).fill(0).map((_, i) => i);
for (
const x of arr
.filter(isEven)
.map(add_one)
) {
// console.log('arr evens incr', x)
}
console.timeEnd("arr");
type Result<T, E> =
| { value: T }
| { error: E }
function resultOk<T, E>(value: T): Result<T, E> {
return { value }
}
function resultErr<T, E>(error: E): Result<T, E> {
return { error }
}
function* chainResult<T, E>(res: Result<T, E>) {
if ('error' in res) {
throw res.error;
}
return res.value;
}
function* bar(a: Result<number, string>, b: Result<number, string>) {
try {
const x = yield* chainResult(a);
const y = yield* chainResult(b);
return x + y;
} catch (e) {
return e as string
}
}
console.log(
bar(
resultOk<number, string>(2),
resultOk(2),
).next().value
)
console.log(
bar(
resultOk<number, string>(2),
resultErr("boom!"),
).next().value
)
function* optionOf<T>(value: T | null) {
if (value === null) {
throw null;
}
return value;
}
function* foo(a: string | null, b: string | null) {
try {
const x = yield* optionOf(a);
const y = yield* optionOf(b);
return `${x} ${y}`
} catch (e) {
return e as null
}
}
console.log(foo("hello", "world").next().value)
console.log(foo("hello", null).next().value)
class Maybe<T> {
constructor(private value: T) {}
static of<T>(value: T) {
return new Maybe(value);
}
then<K>(callback: (value: NonNullable<T>) => Maybe<K>, rej: (err: null) => void) {
if (this.value === null) {
rej(null);
} else {
callback(this.value as any);
}
}
}
async function fn(x: number | null) {
try {
const a = await Maybe.of(x);
const b = await Maybe.of(1);
console.log(a + b);
} catch {
console.log();
}
}
fn(null)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment