Skip to content

Instantly share code, notes, and snippets.

View luizmb's full-sized avatar

Luiz Rodrigo Martins Barbosa luizmb

  • London, UK
View GitHub Profile
@luizmb
luizmb / three-shades-of-mock.swift
Last active March 22, 2021 20:24
Three Shades of Mock
let urlRequest = URLRequest(url: URL(string: "https://my.api.com")!)
// Option 1: Typealias to closure
typealias URLRequester1 = (URLRequest) -> AnyPublisher<(data: Data, response: URLResponse), URLError>
enum URLRequesterNamespace {
static var prod: URLRequester1 = { req in URLSession.shared.dataTaskPublisher(for: req).eraseToAnyPublisher() }
static func mock(alwaysReturns: (data: Data, response: URLResponse)) -> URLRequester1 {
return { _ in
@luizmb
luizmb / CombineAPI.swift
Created December 8, 2020 18:32
How to write a basic HTTP API in Swift using Combine
import Combine
public enum APIError: Error {
case urlError(URLError)
case invalidResponse(URLResponse)
case decodingError(DecodingError)
case unknownError(Error)
}
extension Publisher where Output == (data: Data, response: URLResponse), Failure == URLError {
public func decode<T: Decodable, Decoder: TopLevelDecoder>(type: T.Type, decoder: Decoder) -> AnyPublisher<T, APIError>
@luizmb
luizmb / ProfunctorWritableKeyPath.swift
Last active July 20, 2020 14:25
Comparison between Binding and Endo when lifting by WritableKeyPath
import Foundation
import SwiftUI
// As pointed by @pointfreeco (no pun intended) here https://twitter.com/pointfreeco/status/1285209505714843648
// these types can't be called Profunctor as they are covariant and contravariant on the very same element (single
// generic parameter, instead of 2). That way, function "dimap" here is academically incorrect and either contramap
// or pullback should be used, instead.
struct Endo<Value> {
let run: (Value) -> Value
@luizmb
luizmb / Applicative Reader.swift
Last active December 14, 2019 16:38
Using Reader as Applicative vs Monad, in Swift
import Combine
import Foundation
import PlaygroundSupport
struct Reader<E, A> {
let run: (E) -> A
func map<B>(_ fn: @escaping (A) -> B) -> Reader<E, B> {
Reader<E, B> { e in
fn(self.run(e))
}
@luizmb
luizmb / Playground.swift
Created August 7, 2018 20:12
Pointfree Parallel Playground test
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
struct Promise<A> {
let subscribe: (@escaping (A) -> Void) -> Void
}
extension Promise {
func map<B>(_ f: @escaping (A) -> B) -> Promise<B> {
@luizmb
luizmb / Limit.hpp
Last active October 2, 2022 14:29
Simple C++ functional language query interface (LINQ-alike) prototype
#ifndef Limit_hpp
#define Limit_hpp
#include "Linq.hpp"
template<typename T>
class Limit {
private:
unsigned long limit = 0;