What does this function do in Facebook's JavaScript source?
javascript
Solution
The `bagof()` method can be used as a factory creating constant functions (functions always returning the same value).
Even if you use in such a context:
var randomFun = bagof(Math.random());
Invocation of `randomFun()` will always return the same value because `Math.random()` is evaluated only once (eagerly). I guess it is utility method used when some API requires a method and we simply want to pass constant value. Instead of:
giveMeCallback(function() {return 42})
you can simply say:
giveMeCallback(bagof(42))
Problem
I was reading some of Facebook's JavaScript, and came across a curious function that I couldn't figure out the purpose of: ``` function bagof(a) { return function () { return a; }; } ``` As far as I can tell: - `bagof` is a function that accepts the parameter `a`. - `bagof` immediately returns an anonymous function. - The returned function then returns the original parameter `a`. I would assume that the usage of `bagof` would be something like this: ``` newFunction = bagof("This is the data"); console.log( newFunction() ); //Logs "This is the data" ``` What's the point? Why not directly use or store whatever variable or function that was passed into `a`? The source file looks like it contains many utility functions for the application.