`

Javascript partially applied function

阅读更多

 

partially applying a function returns a new function which you can call. Which could be very useful in a lots of situations.

 

 

Below is an exapmle that uses the partially applied functions, the code is as below.

 

 

          String.prototype.csv = String.prototype.split.partial(/,\s*/);
          var results = ("John, Resig, Boston").csv();
          assert(results[1] == "Resig", "The text value were split properly");
 

 

 

Below is the content of a js file called partials.js file. 

 

 

/**
*@Summary: this function allow curry some functions further
*/
Function.prototype.curry = function () {

var fn = this, args = Array.prototype.slice.call(arguments);

return function () {
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};

/**
* @Summary: 

e.g.

String.prototype.csv = String.prototype.split.partial(/,\s* /);
// or you can do with the following, by specifying the undefine explicitly
String.prototype.csv = String.prototype.split.partial(/,\s* /, undefined);

var results = ("John, Resig, Boston").csv();
assert(results[1] == "Resig", "The text values were split properly");


*/
Function.prototype.partial = function () {
  var fn = this, args = Array.prototype.slice.call(arguments);
  //  alert("length of arguments = " + args.length);



  return function () {
    var arg = 0;
    for (var i = 0; i < args.length && arg < arguments.length; i++) {
      if (args[i] == undefined)
        args[i] = arguments[arg++];
    }


    return fn.apply(this, args);
    //    return fn.apply(document.getElementById("bindbtn"), args);
  };
};
 

 

 

 

 

 

 

 

the code above has impl of partial function on the Function.prototype object.

 

And you have many application situation that you can apply the paritally applied functions. For one, you can have a partial time out function .

 

 

 

 

                var delay = setTimeout.partial(undefined, 1000);

                test("delayed partial function", function () {
                  delay(function () {
                    assert(true, "A call to this function will be temporarily delayed.");
                  });
                });
 

 

 

 

 

 

 

Below is the content of the test file that test the functions of the partials.

 

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type ="text/javascript" src="partials.js"></script>
    <script type="text/javascript" src="../unit.js"></script>
    <script type="text/javascript">
      window.onload = function () {
        test("partials", function () {
          String.prototype.csv = String.prototype.split.partial(/,\s*/);
          // you can do with the line below as well.
          //        String.prototype.csv = String.prototype.split.partial(/,\s*/);
          var results = ("John, Resig, Boston").csv();
          assert(results[1] == "Resig", "The text value were split properly");
        });

                var delay = setTimeout.partial(undefined, 1000);

                test("delayed partial function", function () {
                  delay(function () {
                    assert(true, "A call to this function will be temporarily delayed.");
                  });
                });

        // there is a bug in that addEventListener is not  an object or is null;
        //  the object that is bound to this is as follow.
        //    'this = [object DOMWindow]'
//        var bindclick = document.getElementById("bindbtn").addEventListener.partial("click", undefined, false);
//        test("curry bind function", function () {
//          bindclick(function() { 
//             assert(true, "Click event bound via curried function.");
//                 });
//        });
      };
    </script>

    <style type="text/css" >
      #results li.pass { color: Green }
      #results li.fail { color: Red }
    </style>

</head>
<body>
<ul id="results" />
<input type="button" id="bindbtn" value="click me" />
</body>
</html>
 

 

 

 

 

 

However, from the Javascript  ninja, there it allege that you can do the partial on the addEventListener, well, according to my test, it does not work . 

 

the reason is (as stated in the comment, addEventListener is not a function? if you add something like alert('this = ' + this) in the partial function, you will find that it print out something like 

 

 

 

 'this = [object DOMWindow]'
 

 

 

 

 

 

分享到:
评论

相关推荐

    A Reconfigurable Beam-Scanning Partially Reflective Surface (PRS) Antenna

    A novel reconfigurable partially reflective surface (PRS) antenna is presented in this paper. The beam scanning ability is realized by employing a reconfigurable PRS structure and a phased array as ...

    PDF-FunctionalProgramminginScala-英文版.rar

    书中会详细介绍如何定义和使用高阶函数,以及如何通过柯里化(Currying)和部分应用(Partially Applied Function)来构造更灵活的函数。 其次,函数式编程中的纯函数(Pure Function)是无副作用的,输入与输出...

    js代码-柯里化函数

    柯里化的本质是部分应用(Partially Applied Function),即将函数的部分参数提前应用,得到一个新的只差剩余参数的函数。这样可以简化复杂函数的调用,提高代码的可读性和复用性。 在`main.js`中,我们可以预期...

    How To Model a Partially Reflective and Partially Scattering Surface

    ### 如何在ZEMAX中建模部分反射与部分散射表面 在光学设计领域,理解和模拟复杂的光行为是至关重要的。特别是在非顺序光学(Non-Sequential)领域,建模部分反射与部分散射的表面变得尤为关键。...

    PV_MPPT_Partially.slx带有粒子群算法

    标题中的“PV_MPPT_Partially.slx带有粒子群算法”指的是一个Simulink模型,该模型用于太阳能光伏(PV)系统的最大功率点跟踪(Maximum Power Point Tracking, MPPT)并应用了粒子群优化(Particle Swarm ...

    应用组合学Applied Combinatorics

    4. 离散结构:在组合学中,离散结构通常指的是图论(graph theory)和偏序集(partially ordered sets,简写为posets)。图论是研究顶点和边构成的图形的学科,它在解决网络设计、电路设计等问题时极为重要;偏序集...

    deblur_saturation_v0.1.tar.gz_Deblurring_Shaken_partially satura

    图像去模糊的代码,可以直接应用。Deblurring Shaken and Partially Saturated Images

    js代码-bind的用法

    这对于部分应用(Partially Applied Function)非常有用: ```javascript function greet(name, greeting) { console.log(greeting + ', ' + name); } let sayHelloToAlice = greet.bind(null, 'Alice', '...

    Notes on Partially Ordered Monoids

    偏序幺半群是数学中的一个重要概念,它涉及抽象代数、序结构以及泛代数等多个数学分支。在这篇论文中,刘鹏远、杨义川和Muhammad Zafrullah三人探讨了偏序幺半群中的一些重要性质,并对这些性质进行了深入的研究。...

    FunctionalProgramming:回购用于收集我的函数式编程进度

    咖喱化,或称为部分应用(Partially Applied Function),是函数式编程中的一个重要特性,尤其在JavaScript这样的语言中,它可以将接受多个参数的函数转换为一系列只接受一个参数的函数。这样做的好处是可以提前固定...

    Experimental determination of the azimuthal and radial mode orders of a partially coherent LGpl beam (Invited Paper)

    the azimuthal order and radial order) of a partially coherent LGpl beam (i.e., a partially coherent vortex beam) based on the measurement of the cross-correlation function (CCF) and the double ...

    ELMM_toolbox.zip

    - CLSU.m : function performing the standard partially constrained least squared unmixing. - SCLSU.m: function performing a scaled version of CLSU, which follows a particular case of the ELMM - soft.m:...

    Learning to Rank with Partially-Labeled Data

    ### 排序学习与部分标记数据 #### 一、引言 在信息检索(Information Retrieval,IR)领域,排序算法扮演着至关重要的角色。这类算法的目标是适当地对一组对象或文档进行排序,以便更好地满足用户的查询需求。...

    Partially coherent vortex beams propagation in a turbulent atmosphere

    Based on the Rytov approximation and the cross-spectral density approximation for the mutual coherence function of the partially coherent field, the propagation properties of the partially coherent ...

    An Adaptive Semiparametric Estimation for Partially Linear Models

    在处理数据分析时,部分线性模型是一种重要的统计模型,它结合了线性和非线性因素,在模型的某些变量上使用线性回归,在其他变量上使用非参数方法。本文由王凯平和林路撰写,研究了针对部分线性模型非参数部分的一种...

    Segments and directed partially ordered fields with negative squares

    本文研究了段和有负平方的定向域之间的关系。为了深入理解这一主题,我们需要介绍几个数学领域的概念。 首先,线性序域(Linearly Ordered Field)是一个数学上的结构,其元素可以排序,并且满足完全有序域的特性。...

    Partially Coherent Detection in Rapidly Time Varying Channels的中文翻译

    《部分相干检测在快速时间衰变信道》的中文翻译主要探讨了在快速衰变信道中,如何通过部分相干检测提高通信系统的性能。这部分内容是针对无线通信领域,特别是那些需要在快衰环境中保持稳定服务的应用,如高速无线...

Global site tag (gtag.js) - Google Analytics