Skip to content

Commit 44575f4

Browse files
committed
test(localStorageSpec): test serialization numbers , issue #99
1 parent fd2fc27 commit 44575f4

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

src/angular-local-storage.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ angularLocalStorage.provider('localStorageService', function() {
118118
// Let's convert undefined values to null to get the value consistent
119119
if (typeof value === "undefined") {
120120
value = null;
121-
} else if (angular.isObject(value) || angular.isArray(value) || angular.isNumber(value)) {
121+
} else if (angular.isObject(value) || angular.isArray(value) || angular.isNumber(+value || value)) {
122122
value = angular.toJson(value);
123123
}
124124

@@ -168,13 +168,19 @@ angularLocalStorage.provider('localStorageService', function() {
168168
return null;
169169
}
170170

171-
if (item.charAt(0) === "{" || item.charAt(0) === "[" || angular.isNumber(+item || item)) {
171+
if (item.charAt(0) === "{" || item.charAt(0) === "[" || isStringNumber(item)) {
172172
return angular.fromJson(item);
173173
}
174174

175175
return item;
176176
};
177177

178+
// Test if string is only contains numbers
179+
// e.g '1' => true, "'1'" => true
180+
function isStringNumber(num) {
181+
return /^-?\d+\.?\d*$/.test(num.replace(/["']/g, ''));
182+
}
183+
178184
// Remove an item from local storage
179185
// Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
180186
var removeFromLocalStorage = function (key) {

test/spec/localStorageSpec.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,38 @@ describe('localStorageService', function() {
188188
);
189189
});
190190

191+
it('should be able to set and get integers', function() {
192+
inject(
193+
addItem('key', 777),
194+
expectAdding('ls.key', angular.toJson(777)),
195+
expectMatching('key', 777)
196+
);
197+
});
198+
199+
it('should be able to set and get float numbers', function() {
200+
inject(
201+
addItem('key', 123.123),
202+
expectAdding('ls.key', angular.toJson(123.123)),
203+
expectMatching('key', 123.123)
204+
);
205+
});
206+
207+
it('should be able to set and get strings', function() {
208+
inject(
209+
addItem('key', 'string'),
210+
expectAdding('ls.key', 'string'),
211+
expectMatching('key', 'string')
212+
);
213+
});
214+
215+
it('should be able to set and get numbers as a strings', function() {
216+
inject(
217+
addItem('key', '777'),
218+
expectAdding('ls.key', angular.toJson('777')),
219+
expectMatching('key', '777')
220+
)
221+
});
222+
191223
it('should be able to get items', inject(
192224
getItem('key'),
193225
expectGetting('ls.key')

0 commit comments

Comments
 (0)