[Javascipt] Immediately-Invoker 2

本文介绍如何使用JavaScript构建一个队列,将一系列函数串联起来,实现数字输入到结果输出的流程。通过实例演示了如何创建`applyAndEmpty`函数,用于将数字和队列中的函数进行结合,并最终展示每一步的结果。

Now the people at Poplar Puzzles would like you to treat an array of functions like a Queue, passing the result of each function into the next until the Queue is empty. They’ve sent you the new queue of functions, and a “simple directive”:

In a variable called applyAndEmpty, build and store a function that takes in a single number and any Queue of functions as inputs and then applies the Queue’s functions in order to the input number, where the results of each function become the next function’s input. Additionally, the queue should be empty following your application. Lastly, because we are just that freaking awesome, any loops you use must only be for-loops. MWAHAHA. Then call your new function using the number 2 and the provided puzzlers queue as initial inputs, and alert the result.- PuZzLe MaSTeRs

The new Queue of functions to use is below.

var puzzlers = [
  function ( a ) { return 8*a - 10; },
  function ( a ) { return (a-3) * (a-3) * (a-3); },
  function ( a ) { return a * a + 4; },
  function ( a ) { return a % 5; }
];

We’ve provided the queue and the start value for you.

var puzzlers = [
  function ( a ) { return 8*a - 10; },
  function ( a ) { return (a-3) * (a-3) * (a-3); },
  function ( a ) { return a * a + 4; },
  function ( a ) { return a % 5; }
];
var start = 2;
var applyAndEmpty = function(num){
  puzzlers.map(function(func){
      var res = func(num);
    num = res;
    alert(res);
        return res;
  });
};
applyAndEmpty(start);

 

function buildNow(){
  
  return (function(){
    
    alert("RUN NOW");
  })(); // <<---- We add '()', so that as soon as this function return, it will Immediately invoke.
}
buildNow();


function buildWhenICall(){
  
  return function(){
    
    alert("You call me!");
  };
}

buildWhenICall()(); // <<--- Or we can do something like that
// The same as
//var run = buildWhenICall();
//run();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值