jueves, 20 de diciembre de 2012

Javascript Kata String Reverse

Code in javascript
String.prototype.reverse = function(){
 var result = [];
 var values =  this.split('');
 for(var cont = 0; cont < values.length; cont++){
   result.unshift(values[cont]);
 }
 return result.join('');
}

Test with Jasmine
describe("StringReverse", function () {
    describe("Funcionatity", function(){

        it("Reverse two characters", function () {
            var value = 'va';
            expect(value.reverse()).toEqual('av');
        });

        it("Reverse three characters", function () {
            var value = 'val';
            expect(value.reverse()).toEqual('lav');
        });

        it("Reverse number with three digits", function () {
            var value = '123';
            expect(value.reverse()).toEqual('321');
        });

        it("Reverse complex line text", function () {
            var value = 'q1w2e3r4t5y6u7i8o9p0';
            expect(value.reverse()).toEqual('0p9o8i7u6y5t4r3e2w1q');
        });
    });
});

ScreenShot with the final result

Profesionalidad

Copio literalmente el artículo de Antonio Elena porque me ha parecido excelente. Otra cosa es que lo viva.


La honradez y la sinceridad son las mejores políticas, aunque no lo parezcan a largo plazo. Esta es una breve lista cuya mayoria de elementos casi siempre olvidamos en nuestro día a día. Yo el primero.
  • Se sincero siempre.
  • Acepta la responsabilidad de lo que dices. Tus afirmaciones, tus opiniones, son tuyas.
  • Admite tus errores. No pasa nada. Todo el mundo se equivoca. Admítelos sin vergüenza. Hazlos públicos. En realidad la gente, o las buenas personas, siempre aprecian la transparencia.
  • De la misma, manera no te preocupe mostrar desacuerdo, siempre con educación, cuando te mientan, tergiversen tu información o no sean claros contigo.
  • Expresa tus opiniones siempre de forma constructiva, buscando la conciliación, pero sin tener miedo de expresarlas.
  • Aprende a decir no.
  • Se amable. Agradece con sinceridad el esfuerzo de los demás o habla con ellos cuando tengas algo que objetar.
  • No hables mal a las espaldas de la gente. No enredes, no desinformes.
Si sigues estas guías, deberías poder esperar que los demás también lo hicieran, pero si no, tu ética es la que es. Hay una cita famosa, que no se de quién es, que viene a decir, “no podemos romper la ley, nos rompemos nosotros ocontra la ley”. El original inglés queda mejor, “we cannot break the law, we break ourselves against the law,” y es que el hecho de actuar en contra de nuestro principios solo nos vas a perjudicar a nosotros mismos.
Practicar esto día a día requiere constancia, atención voluntaria y dedicación, pero los resultados son siempre positivos, si bien es un esfuerzo que en solitario lleva bastante tiempo. Mejora tu ambiente laboral, y las relaciones con tus jefes o con los que dependen de ti o tus iguales en tu equipo. Con los clientes, quizás sea más discutible, pero a la larga creo que es igualmente positivo. Y esa mejora, no tengas duda, contagia el resto de aspectos de tu vida.
Si tu entorno de trabajo es un sitio lleno de mentiras, de tensiones, de peleas o malas palabras, ten por seguro que pronto afectará a facetas de tu vida ajenas a la laboral.

Kata StringBuilder

This Kata consist in Simulate the behaviour of the StringBuilder Class. The framework test is Jasmine

The javascript  class
function StringBuilder(value){
 var buffer = new Array(value);
 this.toString = function(){
  return buffer.join('');
 }
 this.append = function(value){
  buffer.push(value);
 }
 this.clear = function(){
  buffer.length = 1;
 }
}

The tests< br />
describe("StringBuilder", function () {
    
    describe("StringBuilder Constructor", function () {
        it("Empty Constructor", function(){
            var stringBuilder =  new StringBuilder('');
            expect(stringBuilder.toString()).toEqual('');
        });

        it("Constructor with some value", function () {
            var value = 'value';
            var stringBuilder =  new StringBuilder(value);
            expect(stringBuilder.toString()).toEqual(value);
        });

    });

    describe("Funcionatity", function(){
        it("Append only a value", function () {
            var value = 'value';
            var stringBuilder =  new StringBuilder('');
            stringBuilder.append(value);
            expect(stringBuilder.toString()).toEqual(value);
        });

        it("Append two values", function () {
            var valueOne  = 'valueOne';
            var valueTwo = 'valueTwo';
            var stringBuilder =  new StringBuilder('');
            stringBuilder.append(valueOne);
            stringBuilder.append(valueTwo);
            expect(stringBuilder.toString()).toEqual(valueOne + valueTwo);
        });        

        it("Append three values", function () {
            var valueOne  = 'valueOne';
            var valueTwo = 'valueTwo';
            var valueThree = 'valueThree';
            var stringBuilder =  new StringBuilder('');
            stringBuilder.append(valueOne);
            stringBuilder.append(valueTwo);
            stringBuilder.append(valueThree);
            expect(stringBuilder.toString()).toEqual(valueOne + valueTwo + valueThree);
        });  

        it("Clear values", function () {
            var valueOne  = 'valueOne';
            var valueTwo = 'valueTwo';
            var valueThree = 'valueThree';
            var stringBuilder =  new StringBuilder('');
            stringBuilder.append(valueOne);
            stringBuilder.append(valueTwo);
            stringBuilder.append(valueThree);
            stringBuilder.clear();
            expect(stringBuilder.toString()).toEqual('');
        });        
    });
})

screenshot of all passed tests


viernes, 14 de diciembre de 2012

Simple Herency in Javascript

//May be, I'm wrong and there is a better way 
//for getting simple herency in javascript
function Thing(name){
 this.color = 'black';
 this.name = name;
}

Thing.prototype.sayName =  function(){
 alert('Thing My name is: ' + this.name);
}

Thing.prototype.sayColor = function(){
  alert('My color is: ' + this.color);
}

function Animal(){
 Thing.call(this, "Floppy"); //<--- herency properties with a parameter
 this.age = 12;
}

Animal.prototype = new Thing();    //<--- set herecy functions by prototypes 
Animal.prototype.constructor = Animal; //<-- set constructor of the object Animal

Animal.prototype.sayAge = function(){
  alert('Animal, my age is: ' + this.age);
}

Animal.prototype.sayName =  function(){ //<--- override the mother's function sayName
  alert('Animal My name is: ' + this.name);
}

var dog = new Animal();
dog.color = 'red';
var phone = new Thing('htc');

alert(' phone color: ' + phone.color + ' phone name: ' + phone.name);
alert('dog, age: ' + dog.age + ' dog color: ' + dog.color + ' dog name: ' + dog.name);
phone.sayName();
phone.sayColor();
dog.sayName();
dog.sayAge();

martes, 4 de diciembre de 2012