functional refactoring: love when this happens

So, nice… 😉

function run(ctx) {
var i;
for(i=0; i<stash.length; i++) {
if(logBefore) {
trace(stash[i], ctx);
if(logAfter) {
trace(stash[i], ctx);
// becomes :->
function run(ctx) {
fn.each(function(f) { fn.compose(trace(f, 'before'), f, trace(f, 'after'))(ctx); }, stash);
view raw refactor.js hosted with ❤ by GitHub

Simple example of functional refactoring

I received a couple of request to show more examples of using functional techniques after my ‘Functional JavaScript’ workshop at Cowerks.

So, I’ll be putting out some examples – simple and to the point… Hopefully 😉

// original code
function printTrace(log) {
for (var i = 0; i < log.length; i++) {
var entry = log[i];
var args = entry.args;
var argstring = "(";
for (var j = 0; j < args.length - 1; j++) {
argstring += args[j].toString() + ",";
if (args.length > 0) {
argstring += args[args.length - 1].toString();
argstring += ")";
console.log( + ": " + entry.op + argstring + ' returned: ' + entry.result);
// ...after replacing explicit loops with 'map'
function printTrace(log) { {
console.log( + ": " + entry.op + '(' + entry.args + ')' + ' returned: ' + entry.result);
// ...finally, using shorthand for anonymous functions -'fat arrow' from ES6
function printTrace(log) { => console.log( + ": " + entry.op + '(' + entry.args + ')' + ' returned: ' + entry.result));

JavaScript SPA Framework: less is more

With that in mind, compare this ‘todo’ application implementation done with Hamlet to your favorite framework:

//- Model: ----------------------------------------
items = Observable []
completeAll = Observable(false)
completeAll.observe (val) ->
items.forEach (i) ->
model =
removeFinished: ->
@finished().forEach items.remove
completeAll: completeAll
hideMarkComplete: -> "hidden" unless @items().length
value: Observable ""
items: items
finished: -> @items.filter (item) -> item.checked()
finishedCount: -> @finished().length
unfinished: ->
@items.filter (item) -> !item.checked()
add: (e) ->
return unless e.keyCode is 13
item =
description: @value()
checked: Observable false
class: -> "completed" if item.checked()
@value ""
//- View -----------------------------------------
- item = ->
%input(type="checkbox" @checked)
%span.item(@class)= @description
%h2 Todos by Hamlet
%input(type="text" @value placeholder="What needs to be done?" onkeydown=@add)
%input(type="checkbox" checked=@completeAll)
%span Mark all as complete
- each @items, item
%span.count= @unfinished
%span.count= @finishedCount

One possible way to compose application using OWIN spec

When composing your server apps with OWIN there are many options. OWIN spec is very flexible and it doesn’t  force you into particular application architecture (this is a good thing). So, using standard OWIN middleware components to compose your application is pretty easy and straightforward.

I prefer to clearly (at the assembly level) separate middleware from the server and the application. That makes it easier to work with for a bigger team, and when potentially, application teams are not the same as server and/or middleware team. Organizing your application in this way could look something like this, starting with middleware components project:

namespace Simplr.Middleware {
public class ResourceResolver : MiddlewareBase {
public override Task Process(IContext context) {...}
public class HypermediaValidator : MiddlewareBase {
public override Task Process(IContext context) {...}
//additional middleware components

and then application is configured and ran like this:

using Simplr.Middleware;
namespace App.Runner {
internal static class Program {
static void Main() {
var _pipeline = new Pipeline()
.Use(new ResourceResolver())
.Use(new HypermediaValidator())
.Use(new ApiCall())
.Use(new HypermediaUpdater())
.Use(new HALSerializer());
var host = new Host(pipeline);
host.AddServer("RequestResponse", new NowinServer(8080));
Console.WriteLine("Listening on port 8080. Enter to exit.");

So, having this in place, application developers – potentially different team(s) then middleware team – would write:

using SimplR.Resources;
using SimplR.Hypermedia;
using SimplR.Services;
using App.Domain.Users;
namespace App.Resources.Users {
public class UsersResource : Resource<User> {
public override List<User> Get() {...}
public override User Get(int id) {...}
public override User Post(User user) {...}
public override User Put(User user) {...}
public override void Delete(int id) {...}
// additional resources
view raw hosted with ❤ by GitHub

which models application interface as resources, and exposes them via standard HTTP verbs…

If you prefer CQRS – you can have middleware dispatch to handlers and then write your applications something like this:

using SimplR.Resources;
using SimplR.Hypermedia;
using SimplR.Services;
using App.Domain.Users;
namespace App.Handlers.Users {
public class UsersHandler : IHandler<User> {
public List<User> Query(Expression expr) {...}
public void CreateCommand(User user) {...}
public void UpdateCommand(User user) {...}
public void DeleteCommand(User user) {...}

Bottom line, OWIN is awesome.

Function oveloading in JavaScript

I was trying to get different behavior from the function depending on its arguments, a feature found in various programming languages such as Ada, C++, C#, Delphi, D, and Java, that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function” – but not in JavaScript. It has been argued that method overloading is not such a good idea (Bertrand Meyer: Overloading vs Object Technology), and in JavaScript using different function names seems to be a right way to go…

But, the interface for the user of this api in that case would look like this:

[gist /]

but I didn’t want that. I wanted this:

[gist /]

Turned out to be easy to add a wrapper on top of the explicitly named api:

[gist /]

Simple Continiuos Integration with FAKE and windows scheduler #fsharp

Below are the details about a very simple CI setup,  the one that simply checks GitHub for changes to ‘master’ and if

there were any, runs FAKE build script.

First FAKE script:

#r @"../_tools/FAKE/FakeLib.dll"
#r @"../_tools/FAKE/MyFakeTasks.dll"
open Fake
open System.IO
open MyFakeTasks
let author = ["Srdjan Strbanovic"]
let release = @".\WinService\bin\release"
let debug = @".\WinService\bin\debug"
let winservice = !! @".\WinService\WinService.csproj"
Target? Clean <-
fun () ->
CleanDirs [release;debug]
Target? Build <-
fun () ->
MSBuildRelease release "Clean" winservice
|> Log "Clean Release Build:"
MSBuildRelease release "Build" winservice
|> Log "Release Build:"
Target? Default <-
fun () -> trace "Finished..."
==> "Build"
=?> ("Default", GitTasks.Pull(@".\") = 1)
Run? Default
view raw build.fsx hosted with ❤ by GitHub

The only part that should be interesting (the rest is standard FAKE) is conditional dependency for ‘Default’ task.

It depends on returned value from a custom FAKE task that checks if there are changes on GitHub.

Here is the custom task:

using System;
using System.Diagnostics;
using System.Linq;
namespace MyFakeTasks
public class GitTasks
public static int Pull(string workingDirectory)
var processStartInfo = new ProcessStartInfo();
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.FileName = @"C:\Program Files (x86)\Git\bin\git.exe";
processStartInfo.UseShellExecute = false;
var result = gitPull(processStartInfo, workingDirectory);
return result;
static int gitPull(ProcessStartInfo processStartInfo, string workingDirectory)
var process = new Process();
processStartInfo.Arguments = "pull";
processStartInfo.WorkingDirectory = workingDirectory;
process.StartInfo = processStartInfo;
var stdErrStr = process.StandardError.ReadToEnd();
var stdOutStr = process.StandardOutput.ReadToEnd();
Console.Write(stdErrStr.Any() ? stdErrStr : stdOutStr);
return stdOutStr.Contains("Already up-to-date.") ? 0 : 1;
view raw gistfile1.cs hosted with ❤ by GitHub

That is all – “simple” is the keyword  🙂 – here is the screenshot of it running:


Till next time…