Skip to content

Instantly share code, notes, and snippets.

View bijancn's full-sized avatar

Bijan Chokoufe Nejad bijancn

View GitHub Profile
package client
import chandu0101.scalajs.react.components.elementalui._
import japgolly.scalajs.react.component.Scala.Unmounted
import japgolly.scalajs.react.vdom.html_<^._
import japgolly.scalajs.react.{ BackendScope, Callback, ReactEventFromInput, ScalaComponent }
import scala.scalajs.js
import scala.scalajs.js.`|`
@bijancn
bijancn / Bifunctor.scala
Created May 18, 2018 18:36
Lessons learned from a fistful of functors
// Do you know this annoying feeling when you repeat a small function twice? Like
val x = X.doSomeStuff.notWorthRefactoring.butAnnoying
val y = Y.doSomeStuff.notWorthRefactoring.butAnnoying
// Now I can replace it with this satisfying pattern
val func = (_: String).doSomeStuff.notWorthRefactoring.butAnnoying
val (x, y) = (X, Y).bimap(func, func)
def buyCoffees(creditCard: CreditCard, n: Int): (List[Coffee], Charge) = {
val purchases = (1 to n).map(i => buyCoffee(creditCard, i))
val (coffees, charges) = purchases.unzip
val reducedCharge = charges.reduce((c1, c2) =>
Charge(c1.creditCard, c1.amount + c2.amount))
(coffees, reducedCharge)
}
trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}
@bijancn
bijancn / countSpaces.scala
Created May 30, 2018 08:46
Don't do this at home
def countSpaces(word: List[Char]): Int = {
var i = 0
var count = 0
while (i <= word.length) {
if (word(i) == ' ') {
count += 1
}
i += 1
}
count
@bijancn
bijancn / addThree.scala
Created May 30, 2018 08:52
Don't do this at home
def addThree(list: List[Int]): List[Int] = {
var i = 0
var result = new ListBuffer[Int]()
while (i < list.length) {
result += list(i) + 3
i += 1
}
result.toList
}
def addThree(list: List[Int]): List[Int] = {
val f = (item: Int) => item + 3
list.map(f)
}
trait Foldable[F[_]] {
def foldLeft[A, B](fa: F[A], b: B)(f: (B, A) => B): B
}
def countSpaces(word: List[Char]): Int =
word.foldLeft(0)((count: Int, char: Char) =>
if (char == ' ') {
count + 1
} else {
count
}
)
def countSpaces(word: List[Char]): Int =
word.count(_ == ' ')