Commits

Keiji Matsuzaki  committed 710381f

add question_4/sample_2

  • Participants
  • Parent commits ec318a7

Comments (0)

Files changed (2)

File question_4/sample_2/index.html

+<!DOCTYPE html>
+<html>
+  <head>
+    <title>pollution sample 2</title>
+    <meta charset="UTF-8"/>
+    </head>
+  <body>
+    <div>
+      <h1>pollution sample 2</h1>
+    </div>
+    <div id="odds-elements">
+    </div>
+    <script type="text/javascript" src="pollution.js"></script>
+  </body>
+</html>

File question_4/sample_2/pollution.js

+(function(window){
+  function validation_arguments(args){
+    if (args.length < 2){
+      throw "require arguments callback and list"; 
+    }
+    var cb = args[0], xs = args[1];
+    if (Object.prototype.toString.call(cb).search(/Function/) == -1){
+      throw "not cb is function.";
+    }
+    if (Object.prototype.toString.call(xs).search(/Array/) == -1){
+      throw "not xs is array.";
+    }
+  }
+
+  var MyApp = {
+    map: function(cb, xs){
+      var args = Array.prototype.slice.call(arguments);
+      validation_arguments(args);
+      var cb = args[0], xs = args[1]
+        , _l = xs.length, _r = []; 
+      for(var i = 0; i < _l; _r.push(cb(xs[i++])));
+      return _r;
+    },
+    filter: function(cb, xs){
+      var args = Array.prototype.slice.call(arguments);
+      validation_arguments(args);
+      var cb = args[0], xs = args[1]
+        , _l = xs.length, _r = [];;
+      for(var i = 0; i < _l; i++){
+        if (cb(xs[i])){
+          _r.push(xs[i]);
+        }
+      } 
+      return _r; 
+    }
+  };
+
+  window.MyApp = window.$ = MyApp;
+})(window);
+
+if(document.addEventListener){
+  document.addEventListener("DOMContentLoaded", run, false);
+}
+
+function run(){
+  var ary_1 = $.map(function(x){ return x * 2; }, [1,2,3,4,5]);
+  var ary_2 = $.filter(function(x) { return (x % 2 == 0 ? true : false); }, [1,2,3,4,5]);
+  var odds_elements = document.getElementById("odds-elements");
+  odds_elements.innerHTML = '<div><span>map: ' + ary_1.join(', ') + '</span></div><div><span>filter: ' + ary_2.join(', ') + '</span></div>';
+}