From 44575f4028c398ea08237d4ed8a95b9f72de7418 Mon Sep 17 00:00:00 2001 From: Ariel Mashraki Date: Tue, 7 Oct 2014 00:25:09 +0300 Subject: [PATCH] test(localStorageSpec): test serialization numbers , issue #99 --- src/angular-local-storage.js | 10 ++++++++-- test/spec/localStorageSpec.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/angular-local-storage.js b/src/angular-local-storage.js index f40c260..3701bed 100644 --- a/src/angular-local-storage.js +++ b/src/angular-local-storage.js @@ -118,7 +118,7 @@ angularLocalStorage.provider('localStorageService', function() { // Let's convert undefined values to null to get the value consistent if (typeof value === "undefined") { value = null; - } else if (angular.isObject(value) || angular.isArray(value) || angular.isNumber(value)) { + } else if (angular.isObject(value) || angular.isArray(value) || angular.isNumber(+value || value)) { value = angular.toJson(value); } @@ -168,13 +168,19 @@ angularLocalStorage.provider('localStorageService', function() { return null; } - if (item.charAt(0) === "{" || item.charAt(0) === "[" || angular.isNumber(+item || item)) { + if (item.charAt(0) === "{" || item.charAt(0) === "[" || isStringNumber(item)) { return angular.fromJson(item); } return item; }; + // Test if string is only contains numbers + // e.g '1' => true, "'1'" => true + function isStringNumber(num) { + return /^-?\d+\.?\d*$/.test(num.replace(/["']/g, '')); + } + // Remove an item from local storage // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular' var removeFromLocalStorage = function (key) { diff --git a/test/spec/localStorageSpec.js b/test/spec/localStorageSpec.js index 8116fd6..46157c5 100644 --- a/test/spec/localStorageSpec.js +++ b/test/spec/localStorageSpec.js @@ -188,6 +188,38 @@ describe('localStorageService', function() { ); }); + it('should be able to set and get integers', function() { + inject( + addItem('key', 777), + expectAdding('ls.key', angular.toJson(777)), + expectMatching('key', 777) + ); + }); + + it('should be able to set and get float numbers', function() { + inject( + addItem('key', 123.123), + expectAdding('ls.key', angular.toJson(123.123)), + expectMatching('key', 123.123) + ); + }); + + it('should be able to set and get strings', function() { + inject( + addItem('key', 'string'), + expectAdding('ls.key', 'string'), + expectMatching('key', 'string') + ); + }); + + it('should be able to set and get numbers as a strings', function() { + inject( + addItem('key', '777'), + expectAdding('ls.key', angular.toJson('777')), + expectMatching('key', '777') + ) + }); + it('should be able to get items', inject( getItem('key'), expectGetting('ls.key')