Javascript skill evaluation
Andrei
by Alexandre Azevedo
HTML
<script src="//searls.github.io/jasmine-all/jasmine-all-min.js"></script>
<script type="application/javascript">
'use strict';
describe('Declaration', function() {
it('is object', function() {
var type = typeof(window.MyFunction);
expect(type).toBe('function');
});
});
describe('Execution of', function() {
var value;
it("initial sequence", function() {
value = new window.MyFunction();
expect(value.current()).toBe(1);
});
it("incrementing sequence once", function() {
value.increment();
expect(value.current()).toBe(1);
});
it("incrementing sequence three times", function() {
value.increment().increment().increment().increment();
expect(value.current()).toBe(8);
});
it("decrementing sequence two times", function() {
value.decrement().decrement();
expect(value.current()).toBe(3);
});
});
</script>
JavaScript
'use strict';
// 1, 1, 2, 3, 5, 8...
// 8
window.MyFunction = function () {
this._current = 1;
this._prev = 0;
};
window.MyFunction.prototype.current = function () {
return this._current;
};
window.MyFunction.prototype.increment = function () {
var res = this._prev + this._current;
this._prev = this._current;
this._current = res;
return this;
};
window.MyFunction.prototype.decrement = function () {
if (this._prev > 0)
{
var res = this._current - this._prev;
this._current = this._prev;
this._prev = res;
}
return this;
};