Currying

有時候我們呼叫某個函式,傳入的參數大多數都是一樣,那我們就可以嘗試保留那些重複的參數,而這個過程就是Currying(Curry化)

html:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <script src="https://code.jquery.com/jquery-2.0.3.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Currying</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:

function currying(fn){
    var slice = Array.prototype.slice,
        stored_args = slice.call(arguments, 1);
    return function(){
        var new_args = slice.call(arguments),
            args = stored_args.concat(new_args);
        return fn.apply(null, args);
    };
}
//--angular--//
var mainApp = angular.module('mainApp', []);
mainApp.controller('tableCtrl', ['$scope',function($scope) {
    $scope.new_m = currying(function m(x, y){
      console.log(x+'*'+y);
      return x * y;
    }, 5);
    $scope.new_m2 = currying(function m(x, y ,z ,k){
      console.log(x+'+'+y+'+'+z+'*'+k);
      return (x + y + z) * k;
    }, 5,2,3);
    $scope.change = function() {
      console.log('==change start==');
      console.log('inp:'+$scope.setData);
      console.log('do new_m:');
      console.log($scope.new_m($scope.setData));
      console.log('do new_m2:');
      console.log($scope.new_m2($scope.setData));
      console.log('==change end==');
    };
}]);

console log: 分別輸入1~4

==change start==
inp:1
do new_m:
5*1
5
do new_m2:
5+2+3*1
10
==change end==
==change start==
inp:2
do new_m:
5*2
10
do new_m2:
5+2+3*2
20
==change end==
==change start==
inp:3
do new_m:
5*3
15
do new_m2:
5+2+3*3
30
==change end==
==change start==
inp:4
do new_m:
5*4
20
do new_m2:
5+2+3*4
40
==change end==

參考

results matching ""

    No results matching ""