Skip to content

Instantly share code, notes, and snippets.

operator prefix ~ {}
@prefix func ~(pattern: String) -> NSRegularExpression! {
var error: NSError?
return NSRegularExpression.regularExpressionWithPattern(
pattern,
options: nil,
error: &error)
}
@kourge
kourge / gist:38c1d3a07a5dee9407c0
Created June 4, 2014 21:19
Fun with double arrow / hash rocket in Swift
operator infix => { associativity left }
func => <K : Hashable, V>(key: K, value: V) -> (K, V) {
return (key, value)
}
let pairs: (String, Int)[] = [
"e" => 10,
"t" => 7,
"i" => 2
]
enum Quadrant {
case BottomLeft
case TopLeft
case BottomRight
case TopRight
static func forPoint(point: CGPoint) -> Quadrant {
switch (point.x, point.y) {
case (let x, let y) where x >= 0 && y >= 0:
return .TopRight
func chunk<T : Sliceable where T.Index : Strideable>(
s: T,
#from: T.Index,
#to: T.Index,
#by: T.Index.Stride
) -> GeneratorOf<T.SubSlice> {
var g = stride(from: from, to: to, by: by).generate()
return GeneratorOf<T.SubSlice> {
if let start = g.next() {
@kourge
kourge / davvero.sh
Created July 22, 2016 18:18
wraps around `test` and echoes "true" or "false" depending on exit status
#!/bin/sh
test "$@"
RESULT=$?
if [[ $RESULT -eq 0 ]]; then
echo true
else
echo false
fi
@kourge
kourge / fsa.ts
Last active September 15, 2016 22:21
Type Safe FSAs
export interface Meta<T> {
meta: T;
}
export type AnyType = string | symbol;
export interface Action<Type extends AnyType, Payload> {
type: Type;
payload: Payload;
error?: boolean;
@kourge
kourge / unit.ts
Created January 19, 2017 02:45
Type-safe units in TypeScript
namespace TypeBranding {
// This incurs no runtime cost. It is a purely compile-time construct.
type Meters = number & { __metersBrand: any };
type Miles = number & { __milesBrand: any };
function Meters(i: number): Meters { return i as Meters; }
function Miles(i: number): Miles { return i as Miles; }
let a: Meters;
@kourge
kourge / enum.ts
Last active March 23, 2017 00:05
String enums in TypeScript
export enum Event1 {
SIGN_IN_WALL = 'Sign In Wall' as any,
SIGN_UP = 'Sign Up' as any,
}
{
const x = Event1.SIGN_UP; // type = Event1
const y: number = x;
// Verdict: approach is succint, but incorrectly allows type widening to number.
}
@kourge
kourge / check.go
Created March 7, 2018 20:14
Go: check at compile time if struct S conforms to interface I
var _ I = S{}
@kourge
kourge / interface-extend.ts
Created March 7, 2018 20:28
TypeScript: Extend one interface from another
interface Narrow {
x: number;
y: number;
}
interface Wide extends Narrow {
z: number;
}