-
-
Save jedschneider/99a8bdbcf13f22c4ac46 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Storage = (function() { | |
var uniqueId = 0; | |
function Storage() {} | |
Storage.prototype.add = function(item) { | |
var id = this.generateId() | |
, data = this._toJSON(item); | |
localStorage[id] = data; | |
}; | |
Storage.prototype.generateId = function() { | |
return ++uniqueId; | |
}; | |
Storage.prototype.reset = function() { | |
uniqueId = 0; | |
}; | |
Storage.prototype._toJSON = function(items) { | |
return JSON.stringify(items); | |
}; | |
Storage.prototype._fromJSON = function(json) { | |
return JSON.parse(json); | |
}; | |
return Storage; | |
})(); | |
window.Storage = Storage; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe("Storage", function() { | |
var store; | |
beforeEach(function() { | |
store = new Storage(); | |
store.reset(); | |
}); | |
it("can generate unique ids", function() { | |
var ids = [ | |
store.generateId(), | |
store.generateId(), | |
store.generateId(), | |
store.generateId() | |
]; | |
expect(ids).toEqual([1,2,3,4]); | |
}); | |
it("can reset the id counter", function() { | |
store.generateId(); | |
var last = store.generateId(); | |
expect(last).toEqual(2); | |
store.reset(); | |
last = store.generateId(); | |
expect(last).toEqual(1); | |
}); | |
it("can encode content", function(){ | |
data = {one: 1, two: 2}; | |
encoded = store._toJSON(data); | |
expect(encoded).toEqual('{"one":1,"two":2}'); | |
}); | |
it("can decode content", function(){ | |
data = '{"one":1,"two":2}'; | |
encoded = store._fromJSON(data); | |
expect(encoded).toEqual({one: 1, two: 2}); | |
}); | |
it("can store an item", function() { | |
var data = {item: "Test"}; | |
store.add(data); | |
expect(localStorage[1]).toEqual(JSON.stringify(data)); | |
}); | |
it("can fail", function() { | |
expect(true).toBeFalsy(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment