memory cache

如何用javascript達到memery cache?

用變數暫存

html: (用angularJS協助)

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>YouTube API Uploads via CORS</title>
</head>
<body ng-app="mainApp">
<div class="PageContent">
  <div ng-controller="tableCtrl">
    <input type="text" ng-model="setData"  ng-change="change()">
  </div>
</div>
</body>
</html>

javascript:

var memoize = function(f) {
  var cache = {};
  return function() {
    var arg_str = JSON.stringify(arguments);
    console.log(cache);
    cache[arg_str] = cache[arg_str] || f.apply(f, arguments);
    return cache[arg_str];
  };
};
var call_string = memoize(function(x){
  return 'data'+x;
});

var mainApp = angular.module('mainApp', []);
//==table==//
mainApp.controller('tableCtrl', ['$scope',function($scope) {
    $scope.change = function() {
      console.log('==change start==');
      console.log('inp:'+$scope.setData);
      console.log('do call_string:');
      call_string($scope.setData);
      console.log('==change end==');
    };
}]);

console log: 分別輸入 1 → 12 → 1

==change start==
inp:1
do call_string:
Object {}
==change end==

==change start==
inp:12
do call_string:
Object {{"0":"1"}: "data1"}
==change end==

==change start==
inp:1
do call_string:
Object {{"0":"1"}: "data1", {"0":"12"}: "data12"}
==change end==

參考

results matching ""

    No results matching ""