Skip to content

Instantly share code, notes, and snippets.

val minOffset: Long = if (items.isEmpty) 0 else items.map(_.offset).min
val offset = items.map(_.offset).minOrElse(0)
implicit class ListSyntax[T: Ordering](lst: Iterable[T]) {
def minOrElse(default: T): T = foldOrElse(lst)(_.min, default)
def foldOrElse(lst: Iterable[T])(func: Iterable[T] => T, default: T): T =
if (lst.nonEmpty) func(lst) else default
}
//importing this allows us the syntax we wanted
case class Item(val offset:Int)
val list = List(Item(1),Item(2))
list.map(_.offset).minOrElse(-1) //yields 1
def min[B >: A](implicit cmp: Ordering[B]): A = {
if (isEmpty)
throw new UnsupportedOperationException("empty.min")
//.. does not really matter
}
def reduceLeft.... = //see TraversableOnce.scala code for mroe info
@dorsev
dorsev / time.based.cache.js
Created February 27, 2019 20:41
node-caching in node
const NodeCache = require('node-cache');
module.exports = (refreshTime, loadByKey, logger, cacheName) => {
const myCache = new NodeCache({
stdTTL: refreshTime,
checkperiod: 120
});
return (key, params) => {
const value = myCache.get(key);

Some code I recently ran into in our code-base.

  val minOffset: Long = if (items.isEmpty) 0 else items.map(_.offset).min

What is my problem ?

It is too verbose. Instead of the code telling you what is it's purpose, it is telling you what to do.

An ideal syntax for that would be for me :

package sandbox
import cats.free.Free
import cats.implicits._
object FreeMonadExample extends App {
sealed trait KvStoreA[A]
case class Put[A](key: String, value: A) extends KvStoreA[Unit]
case class Get[A](key: String) extends KvStoreA[Option[A]]
case class Delete[A](key: String) extends KvStoreA[Unit]
type KvStore[A] = Free[KvStoreA, A]
@dorsev
dorsev / JsonCompare.scala
Created September 12, 2019 21:14
DeepEqual in Jsons
import play.api.libs.json._
object Main extends App {
val input= Json.parse("""{"a":1}"""}
val expected= Json.parse("""{"a":1}"""}
def isEqual(a: JsValue, b: JsValue): Boolean = (a, b) match {
case (JsNull, JsNull) => true
case (JsString(str), JsString(str2)) => str == str2
@dorsev
dorsev / dynamicTemplateSchema.sh
Last active December 24, 2019 23:10
dynamic_template schema
curl -X PUT "localhost:9200/_template/my_template?pretty" -H 'Content-Type: application/json' -d '
{
"index_patterns": [
"your-index-names*"
],
"mappings": {
"_doc": {
"dynamic_templates": [
{
"tags": {
curl -X PUT "localhost:9200/my_index_2?pretty" -H 'Content-Type: application/json' -d'
{
"mappings": {
"_doc": {
"properties": {
"tags": {
"type": "object",
"properties": {
"keyToValue": {
"type": "keyword"