Skip to content

Instantly share code, notes, and snippets.

import Foundation
let input: [Any] = [1, [2, 3], [4, [5, 6]]]
let output: [Int] = input.description.characters.filter { !"[] ".characters.contains($0) }.reduce(""){ "\($0)\($1)"
}.components(separatedBy: ",").map{ Int($0)!}
print(output)
func visit<Element>(_ arrayOrSingleItem: Any, with visitor: (Element)->()) {
if let singleItem = arrayOrSingleItem as? Element {
visitor(singleItem)
} else if let array = arrayOrSingleItem as? [Any] {
array.forEach { visit($0, with: visitor)}
}
}
func flatten<Element>(_ untypedItems: [Any], whereElementsAreOfType type: Element.Type) -> [Element] {
var elements = [Element]()
@jmcd
jmcd / OptionModels.cs
Last active February 14, 2017 10:54
Adding strongly typed options (app settings) models to DI container in dotnetcore
public class IdentityOptions
{
public string AuthorityUrl { get; set; }
public string ClientId { get; set; }
}
public class AgencyOptions
{
public string ApiUrl { get; set; }
}
@jmcd
jmcd / SequentialGuidEnumerator.cs
Created February 10, 2017 09:55
Sequential GUIDs for situations needing deterministic data
using System;
using System.Collections;
using System.Collections.Generic;
namespace Foo
{
public class SequentialGuidEnumerator : IEnumerator<Guid>
{
private byte[] bytes;
private readonly byte[] firstBytes;
import UIKit
struct Point {
let x: Double
let y: Double
}
struct Hypotrochoid {
let R: Double
@jmcd
jmcd / FunctionalFactoryExperiment.cs
Last active December 7, 2016 14:02
Creating complex object graph without mutable state or loops; building up and passing context along.
private IEnumerable<Measurement> MakeTestMeasurementRequests()
{
var baseDay = new DateTimeOffset(2000, 1, 1, 0, 0, 0, new TimeSpan(0));
var issuerUrl = GetType().FullName;
const int numberOfUsers = 5;
const int numberOfDaysPerUser = 10;
var kinds = EnumValueTool.GetValues<MeasurementValueKind>();
@jmcd
jmcd / ExtnTuple.cs
Created December 6, 2016 08:29
Example of an extension on a tuple in c#7
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var context = default((IBus, IDatabase));
@jmcd
jmcd / KeyExchange.swift
Last active April 8, 2022 17:37
Diffie–Hellman key exchange simple implementation
import Foundation
protocol Cipher {
func encrypt(message: String, secret: Int) -> String
func decrypt(message: String, secret: Int) -> String
}
struct XOR: Cipher {
private func impl(message: String, secret: Int) -> String? {
@jmcd
jmcd / Availability.cs
Created November 15, 2016 13:59
Availability bitmaps
using System;
using System.Linq;
using NUnit.Framework;
namespace AvailSpike
{
[TestFixture]
public class UseCase
{
[Test]
@jmcd
jmcd / 99bottles.swift
Created October 31, 2016 18:26
Program to print the lyrics to 99 Bottles of Beer
enum Action {
case tookOne
case wentToStore
}
struct Verse {
let countBeforeAction: Int
let action: Action
let countAfterAction: Int
}