Skip to content

Instantly share code, notes, and snippets.

@fResult
Created March 19, 2025 07:10
Show Gist options
  • Select an option

  • Save fResult/982576d49b0ad274ea8aba10777907e2 to your computer and use it in GitHub Desktop.

Select an option

Save fResult/982576d49b0ad274ea8aba10777907e2 to your computer and use it in GitHub Desktop.
type Functor<T> = {
map<R>(fn: (val: T) => R): Functor<R>
concat(other: Functor<T>, combiner: (a: T, b: T) => T): Functor<T>
getValue(): T
}
function id<T>(value: T): Functor<T> {
return {
map<R>(fn: (val: T) => R): Functor<R> {
return id(fn(value))
},
concat(other: Functor<T>, combiner: (a: T, b: T) => T): Functor<T> {
return id(combiner(value, other.getValue()))
},
getValue(): T {
return value
}
}
}
const text = id("Functor Laws")
console.log(text.map(upperCase).map(withTitleLabel).getValue())
function upperCase(x: string): Uppercase<string> {
return x.toUpperCase() as Uppercase<string>
}
function withTitleLabel(x: string): string {
return `Title: ${x}`
}
class Person {
constructor(public fname: string, public lname: string, public age: number) {}
}
class PersonResponse {
constructor(public fullname: string, public age: number) {}
static fromPersonDao({fname, lname, age}: Person): PersonResponse {
return new PersonResponse([fname, lname].join(" "), age)
}
}
const p1 = id(new Person("Korn", "Zilla", 18))
.map(PersonResponse.fromPersonDao)
.concat(id(new PersonResponse("fResult Sila", 30)), (x, y) => new PersonResponse(x.fullname.split(" ")[0] + y.fullname.split(" ")[1], x.age + y.age))
.getValue()
console.log(p1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment