viernes, 25 de diciembre de 2015

functional programming in javascript

Since summer I've been studing functional programming, first of all I started with clojure, later continued to javascript. Actually I studied some functional programming concepts and I applied into javascript, like map, reduce, foreach, monads, ...

Of course been doing tdd, althoguh the tests are not very expressives.

The code lives here.
Some examples of tests

describe("combine filter, map & reduce", function(){
 it("return the result of combination of filter, mal and reduce", function(){
  var data = [1,2,3,4,5,6];
  var resultExpected = 15;

  var result = reduce(
       map(
        filter(
         data, functionForFilter
        ), 
        functionForMap
       ), 
       0, functionForReduce
      );

  expect(resultExpected).to.eql(result);
 });
 function functionForMap(y){
  return y + 1;
 }
 function functionForFilter(x){
  return x % 2 == 0;
 }
 function functionForReduce(acumulative, z){ 
  return acumulative + z;
 }
});

describe("PipeLine object", function(){
 it("make pipe line through different functions", function(){
  var arrayOfData = [1,2,3];
  var expectedResult = 9;
  var handlerOne = function(data){
   return map(data, function(number){
    return number +1;
   });
  }
  var handlerTwo = function(data){
   var result = 0;
   return reduce(data, result, function(result, number){
    return result + number;
   });
  }
  var pipeLine = new PipeLine();

  var pipeLineResult = pipeLine.pipe(handlerOne)
         .pipe(handlerTwo)
         .execute(arrayOfData);

  expect(expectedResult).to.eql(pipeLineResult);       
 });
});

describe("curry function", function(){
  var expectedResult = 10;
  var add = function(a, b, c, d){
   return a + b + c + d;
  }
  var curriedFunction = curry(add);
  beforeEach(function(){});
  it("curry function with all parameters as partial", function(){
   var result = curriedFunction(1)(2)(3)(4); 

   expect(expectedResult).to.eql(result);
  });

  it("curry function with two parameters as partial", function(){
   var result = curriedFunction(1, 2)(3)(4); 
   
   expect(expectedResult).to.eql(result);
  });

  it("curry function with one parameters as partial", function(){
   var result = curriedFunction(1, 2, 3)(4);
   
   expect(expectedResult).to.eql(result);
  });

  it("curry function with parameters as partial in two pairs", function(){
   var result = curriedFunction(1, 2)(3, 4);
   
   expect(expectedResult).to.eql(result);
  });

  it("curry function with parameters as usual", function(){
   var result = curriedFunction(1, 2, 3, 4);
   
   expect(expectedResult).to.eql(result);
  });
 });

Playing with promises in javascript

Reading about callbacks, monads, ... I've tried q library.
Interesting reading about monads and promises, source

This the code.

var fs = require('fs');
var Q = require('q');

function readFile(file){
  var deferred = Q.defer();
  fs.readFile(file, 'utf8', function (err, data) {
    if (err){
   deferred.reject(err);
 } 
    else{
   deferred.resolve(data);
 }
  });
  return deferred.promise;
}

var textFilteContent = readFile('notes.txt');

textFilteContent.then(function(data){
 console.log(data);
}).fail(function(err){
 console.log('error reading the file: ', err);
});

console.log('end');

jueves, 3 de diciembre de 2015

Lean Code Kata

Yesterday I was in an event at Software Craftsmanship Madrid. It was about lean code. The result of the exercise lives in my repo at Github.com. The code could be refactored. But I am learning that early refactoring could be a wrong decision for the future.

jueves, 26 de noviembre de 2015

bind in js

I'm studing functional programming, but in the different way as I've studied at univerity. So I'm coding some tipycal fp functions in javascript. Now is the bind function.

The code lives here

With this song while I'm coding

miércoles, 4 de noviembre de 2015

Playing with socket.io

More and more javascript is the language that the most of the time I'm writting. Some time ago I've discovered web sockets, so I've been playing with it. The result is a simple chat with socket.io library.

The source of the example code 

The code of this example lives in github

Happy hacking

jueves, 8 de octubre de 2015

Setup the current number format

I´ve discovered the new way for setting up numbers in the current country format. I´m from Spain, so the numbers are like 12.345,67.

We can use.

var result = parseInt(simpleNumber).toLocaleString('es-ES');

viernes, 28 de agosto de 2015

Discovering Map function in clojure

Here it's the simple function in clojure using map

(map + [1 2 3] [4 5 6] [7 8 9]) 

then it returns

=> [12 15 18] It's nice an simple ;-)

miércoles, 12 de agosto de 2015

My first function in clojure

This a simple recursive countdown, but in clojure is more interesting. This is the code:
(defn countdown [x]
 (if (zero? x)
  (do 
   :blastoff!
   (println "Zero")
  )
  (do
   (println x)
   (recur (dec x))
  )
 ) 
)

miércoles, 15 de julio de 2015

Translate simple program from Java to Clojure

In Java:
public static double hypot (double x, double y) {
 final double x2 = x * x;
 final double y2 = y * y;
 return Math.sqrt(x2 + y2);
}
In Clojure
(defn hypot [x y]
 (let [x2 (* x x)
  y2 (* y y)]
 (Math/sqrt (+ x2 y2))
  )
)
  The execution
(println (hypot 2 3))

martes, 14 de julio de 2015

My first code in clojure

I've finished reading Javascript The Good Parts. Yesterday a co-worker said to me that I could learn some functional language, He recommend to me Clojure son I've just started with Programming Clojure and this is my first little program:

(defn average [numbers]
 (/ 
 (apply + numbers)
 (count numbers)
 )
)

(println 
 (average [1 2 3 4 5])
)

When I was writing this little piece of code, I've remember when I was at university and I studied Lisp in IA signature.

miércoles, 24 de junio de 2015

List In Javascript

I've finished my new pet project: lists with fluent api and like a linq operations. It lives here
It appeared as a code kata, but it finished like a little library.

some tests

 
it("Given different lists with numbers when call zip method, return a list with zipped elements", function(){
   var numbers = new List([1,3]);
   var result = numbers.zip(new List([2,4,6]));
   expect(result.isEqual(new List([1,2,3,4,6]))).to.be(true);
});

it("Given list with numbers when call skip method then Ignores the specified number of items and returns a sequence starting at the item after the last skipped item (if any)", function(){
   var numbers = new List([1,2,3,4,5,6,7,8]);
   var result = numbers.skip(3);
   expect(result.isEqual(new List([4,5,6,7,8]))).to.be(true);
});

it("Given list with numbers when call apply condition with fluent api", function(){
   var result = new List([1,2,4,3,5,3,7,9])
                    .where(function(x){ return x > 1})
                    .where(function(x){ return x < 5});
    expect(result.isEqual(new List([2,4,3,3]))).to.be(true);
});

describe(".orderBy()", function(){
   it("Given list with numbers when call orderAscending method then returns an list ordered", function(){
      var numbers = new List([{number:5, letra:'e'},{number:3, letra:'q'},{number:1, letra:'a'},{number:9, letra:'w'},{number:4, letra:'r'},{number:7, letra:'t'}]);
      var result = numbers.orderBy(function(x, y){
         return (x.number - y.number);
});
    expect(result.isEqual(new List([{number:1, letra:'a'},{number:3, letra:'q'},{number:4, letra:'r'},{number:5, letra:'e'},{number:7, letra:'t'},{number:9, letra:'w'}])))
.to.be(true);
    });
});

miércoles, 4 de febrero de 2015

Cuando el trabajo se convierte en hobby

Muchas veces pienso que tengo suerte, porque mi trabajo me gusta y además me pagan por ello. No solo eso si no que también es un de mis hobbies.
Cuando llega el domingo por la tarde mucha gente se deprime porque tiene que ir a trabajar al día siguiente, pero personalmente no me siento así. Al igual que cuando me levanto por las mañanas.

domingo, 11 de enero de 2015

Comenzando un nuevo año y una nueva etapa

Hace tiempo que no escribo en el blog.

Como se suele decir. He estado un poco liado. Creo que he batido mi record de días trabajados sin descanso: 21 días, no está mal, ha habido compañeros que han mejorado esta marca. Aunque el record de cantidad de horas trabajadas en el mismo día son15, no lo superé esta vez. Aunque tuve un compañero de piso que su record fueron más de 40 horas.

Este año ha venido con un muy esperado cambio de trabajo. Por el camino han quedado las preguntas de las entrevistas, que me han hecho reir, como ¿estás dispuesto a programar hasta las 3 a.m.? o cosas por el estilo.
Durante estos años he conocido a gente estupenda, tanto en el terreno profesional como en lo personal. He aprendido muchas, muchas cosas. Y ha surgido la inquietud de mejorar de una forma constante, disfruntando del camino andado hasta encontrar la meta deseada.

La vida es una sucesión de etapas y llevaba bastante tiempo notando que tenía que comenzar una nueva.

Ahora comienzo con mucha ilusión, en una empresa que se aleja del sector de la consultoría, centrándonse en vender su propio producto. Se cuida muy mucho lo que se hace y cómo se hace. Es una auténtica pasada. Además a la gente le gusta programar y aprender nuevas cosas.

Me ha llamado la atención un compañero que este viernes me ha dicho que el fin de semana lo iba a emplear en estudiar la gramática de una lengua semítica.

He descubierto a otro autor que me llama la atención. Ludovico Einaudi

Me ha gustado mucho este video de Sergio Fernández

Mirar pá lante con ilusión y optimismo