Title One: Write a JavaScript function calculate, the function has the following properties
Calculate () = 0;calculate (2) () = 2;calculate (3) (4) (1) (5) () = 13;
That is, you can chain calls consecutively, and once a call has no arguments, the and of all previous parameters is returned.
In fact, the topic itself is not complicated, the code is very simple, is a bit around the idea, it may be repeated on the computer to try the tune to write the right, the answer is as follows:
var calculate = (function () { var sum = 0; var func = function () { if (arguments.length = = = 0) { var ret = sum; sum = 0; return ret; } Sum + = arguments[0]; return func; }; return func;}) (); Console.log (Calculate ()); Output 0console.log (Calculate (100) ()); Output 100console.log (Calculate (1) (2) (3) (4) ()); Output 10
The main idea is to record the current result with a closure variable, and once the function has no parameters, it returns a numeric result, once it has a parameter, records the current and then returns the function itself.
Topic Two: There is a JS function, the function is called the app, it satisfies the following properties:
var func1 = function (next) { console.log (' func1 begin '); Next (); Console.log (' func1 end ');}; var func2 = function (next) { console.log (' FUNC2 begin '); Next (); Console.log (' Func2 end ');}; var func3 = function (next) { console.log (' func3 begin '); Next (); Console.log (' func3 end ');}; var a = new APP (); A.use (func1); A.use (FUNC2); A.use (func3); A.run ();//output://func1 begin//func2 begin//func3 begin//Fu Nc3 end//func2 end//func1 End
A bit like middleware, after the app is instantiated, you can register a series of functions with the use method, and then run the registered function through the Run method, the registered function accepts a next function as an argument, and once the next executes, the next registration function is called recursively. Please write out the implementation of this function of the app.
Just see this topic when a bit of a circle, feel no pen, think a long time later found ... It turned out to be so simple ... Himself in the circle. The answers are as follows:
var APP = function () { this.stack = [];}; APP.prototype.use = function (CB) { This.stack.push (CB);}; APP.prototype.run = function () { var = this; var next = function () { if (Self.stack.length < 1) { return; } var cb = Self.stack.shift (); CB (next); }; Next ();};
Two small questions about JS (closures and middleware)