localStorageをWeb SQL Databaseで代用してみる。(1)

実装しときたいメソッド

メソッド 意味
setItem keyとvalueを指定してlocalStorageに保存する
getItem keyを指定してlocalStorageからvalueを取り出す
removeItem keyを指定してlocalStorageからkey valueのペアを取り除く
clear localStorageの中身を全て取り除く

実際のコードの書き出し。localStorageDBという名前にしてみよう。 既存の実装の置き換えということで、メソッド内部をlocalStorageで実装しておく

(function(w){
  var ls = {};
  ls.setItem = function(key, value){
    return localStorage.setItem(key, value);
  }
  ls.getItem = function(key){
    return localStorage.getItem(key);
  }
  ls.removeItem = function(key){
    return localStorage.removeItem(key);
  }
  ls.clear = function(){
    return localStorage.clear();
  }

  if(!w.localStorageDB){
    w.localStorageDB = ls;
  }
}(window));

空のメソッドだけ用意して次にテストコード。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>localStorage-db test</title>
  <link rel="stylesheet" href="qunit-1.11.0.css" />  
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="qunit-1.11.0.js"></script>
  <script src="localStorage-db.js"></script>
  <script type="text/javascript"> 

test( "setItem result", function() {
  localStorageDB.clear();
  ok(localStorageDB.setItem("key", "value") === undefined, "Passed !");
});

test( "setItem getItem", function(){
  localStorageDB.clear();
  localStorageDB.setItem("key", "value");
  ok( localStorageDB.getItem("key") === "value" , "Passed!" );
});

test( "getItem Nothing result" , function(){
  localStorageDB.clear();
  ok( localStorageDB.getItem("key") === null , "Passed!" );
});

test( "removeItem test" , function(){
  localStorageDB.setItem("key", "value");
  localStorageDB.removeItem("key");
  ok(localStorageDB.getItem("key") === null, "Passed!");
});

test( "clear test" , function(){
  localStorageDB.setItem("key1", "value");
  localStorageDB.setItem("key2", "value");
  localStorageDB.setItem("key3", "value");

  localStorageDB.clear();

  ok(localStorageDB.getItem("key1") === null, "Passed!");
  ok(localStorageDB.getItem("key2") === null, "Passed!");
  ok(localStorageDB.getItem("key3") === null, "Passed!");
 
});
  </script>
</body>
</html>

結果

f:id:mitsugi-bb:20130127163611p:plain