What's the relationship between streamjs and linqjs - javascript

After reading SICP, I recently discovered streamjs. The developer referenced linqjs as an alternate implementation with different syntax, but I can't make the connection. How do the methods in streamjs map to those in linqjs?

I haven't used either library, but, here's my initial analysis (I've read quite a bit of SICP, but not the whole thing admittedly).
stream.js is an implementation of a functional style data structure for a list. Many data structures in a functional language tend to be recursive, much like the Stream structure. It is composed of a head element, and a Stream for the tail (subsequent elements). Here, lazy evaluation can be achieved by allowing the tail to be a function (i.e. infinite sequences).
Now, to answer your question, all of the functions provided by linq.js should be able to be defined with other common higher order functions like map, reduce, walk, fold, etc.
Sure, stream.js does not implement the Any() method from linq.js, but you can just do that with reduce().

I guess they are similar because they pass functions around instead of "scalar values" ,so they can do lazy evaluation ( evaluate the result at the end of the operations / on demand and not at each operation like with classic javascript data structures). I used that principle with my pimple.js library , which has nothing to do with stream or link but uses lazy evalutation.

linq.js and stream.js have the following similarities:
Use functions to implement streams as a data structure
Use streams to implement lazy evaluation of operations
linq.js and stream.js have the following differences:
linq.js has syntactic sugar for querying JSON
stream.js has the ability to chain streams
linq.js has syntactic sugar for set operations
References
LINQ in JavaScript for Real
LINQ in JavaScript, ES6 Style

Related

Mongoose Chained Queries

I'm currently reading this excellent MDN tutorial.
There seems to be two main different ways to perform queries with mogoose, one being more 'functional', using a chained notation.
My question is, does this kind of notation starting with an empty .find() method starts to import all the collection, then filters the successive pointers inside the app, or does it compile the query (the filtering stuff happening on the mongoDB instance) and only performs the callback locally?
The dot-based notation looks nice and cleaner, but if the filter does not get compiled before requests are being made it seems to be a bad idea to import the whole collection on the app for every simple query. Am I right?
If this is the case, are we in one of these situation where we have to favour object composition over function composition (like Eric Elliott said), or is it not the point here?

Can I use JavaScript objects passed to Rust to implement structures that need garbage collection?

When using Rust in a browser, I can get JavaScript objects and use them inside Rust (using, for instance, the js! macro from the stdweb library).
Given that these objects came from JavaScript, can I use them in Rust to implement structures that benefit from garbage collection (for instance, to implement graphs)?
It depends on cost of JS<>Wasm interaction, and the way you're going to use the data.
To get definitive answer you'd have to try a specific algorithm and benchmark it, but in general I don't expect it to be beneficial.
For complex object graphs in Rust you'd use Rc<RefCell<…>>. It has a relatively low overhead, so you'd need to have very GC-friendly usage pattern to beat it, especially given overhead of JS objects.

Why are configuration functions that "return this" common in JavaScript?

It seems to be a common javascript convention to configure objects with methods called one after the other, for example
toy.setColor(blue).setPrice(5).setName('Blocks').setPurchaseAction(function(customer){
...
})
and so on.
Coming from a more java based background I am used to splitting up each of those method calls into separate statements, separated by a semicolon.
It probably doesn't matter when compiled into machine level language but the practice of splitting with semicolons seems like it makes code easier to read/understand. Is there a good reason for doing it like this in javascript?
The pattern is named "method chaining" and the main advantage of such an approach is that when no need exists to hold on to a placeholder at each step then the next method may simply be called as a continuation.
Further, this type of approach is well suited for deferred execution, and many languages use such an approach. In JavaScript you can see this being used in the new-ish promise features which favor method chaining over what some refer to as "callback hell" in JavaScript.
Overall, it is just preference as it does not offer any performance benefits to use method chaining versus iteratively calling methods. However, it does read very nicely in my opinion, and the pattern pairs very well with other similar approaches.

Difference between using _(obj).map(callback) and _.map(obj, callback) in underscore

Is there any difference in approach of invoking map method from the perspective of which data it will return?
I expect that when I do
_(object).map(callback);
it leads to creating new underscore class instance and returned value is an underscore's wrapper
rather than using
_.map(obj, callback)
utilizes the same (already created) instance of underscore and returns plain JavaScript array as expected
It depends. If you don't ever plan on chaining any function calls after or before map(), then there's no point in wrapping the value. On the other hand, structuring chains that applicatively transform collections leads to compact and readable code.
Depending on the structure of your application, wrapper instances can be passed around from function to function, and built upon. This works because they're lazy in the sense that the chained calls aren't actually run till value() is called.
They're also lazy from an evaluation perspective. Here's a good resource on lazy evaluation in lodash.
In all cases, the result of the chained syntax is identical to the non-chained system.
Mostly, the chaining syntax is just a more readable syntax for performing several operations at once.
Most people find this chained syntax:
_(ds)
.groupBy("group")
.map(function(group) {
return _.sample(group, n);
})
.flatten()
.value();
Much more readable than a non-chained syntax:
_.flatten(_.map(_.groupBy(ds), "group", function(group) {
return _.sample(group, n);
}))
But again, both will give you the same result.
However, in lodash, (as of version 3.0) there is a potential performance benefit to using the chaining syntax, as it uses lazy evaluation. This means that it will defer as much evaluation as possible in order to minimize the operations needed to calculate the result, and also to reduce the number of temporary arrays created.
The article Adam Boduch linked on lazy evaluation seems like a good resource, or you can read the overview for Lazy.js, which was essentially a lazy evaluation version of lodash/underscore before lodash supported lazy evaluation itself. Though that one is out of date, in that it doesn't reflect that lazy evaluation has been added to lodash since the time it was written.
Underscore may eventually add lazy evaluation to their chaining syntax eventually but I haven't seen anything to indicate that that's on their roadmap.

Is there a set of restrictions I can use to simulate functional programming in JavaScript?

I was watching a talk on clean code by Misko Hevery, and he mentioned trying to write a program with no if statements in them (well, as few as humanly possible) in order to simulate working on... Smalltalk or some such language, where polymorphism is preferred over inline conditional behavior.
To my limited understanding, functional programming is hard for only-imperative-so-far programmers like me - because our state changing methodologies don't have a way to be expressed in functional programs. A function only takes a value and returns a value and knows nothing about state.
I have also seen JS being hailed as being able to support a functional model.
So is there a simple set of restrictions, similar to my first paragraph, which will enable me to try out the functional paradigm in a language I know and love - rather than learn a full new language (I'll do that eventually but I want to try the ethos right now)?
There are two meanings to the term "functional programming".
The first meaning is the ability of a program to manipulate functions. Not all languages can do this but javascript is one of the languages that can. Languages that can assign functions to variables, pass functions to arguments and return functions are called functional programming languages so javascript is functional as is.
In this sense, if you look at any modern javascript code with prevalent use of callbacks then you're already doing functional programming.
The second meaning of functional programming is the style of programming where the primary method of program composition is functions rather than variables. In this sense almost any language can be used in a functional style by avoiding variable assignments and loop structures (use recursion instead).
When you look at the functional community, what they mean by functional is the first meaning plus a very strong version of the second meaning -- that is, variables are not only avoided but banned. Languages like Haskell don't have the concept of variables. To handle side-effects and mutable state like I/O they use a concept called monads.
You don't have to go that far. Classical functional languages like Lisp and Forth allowed variables. You just have to avoid them where possible.
Lisp and Forth style functional programming is heavily driven by processing lists/arrays without assigning anything to temporary variables. To some people, this style is easier to read. Where in imperative style you'd do this:
var a = [1,2,3];
var b = 0;
for (var i=0;i=a.length;i++) {
b += a[i] * 2;
}
// result is in b
in functional style you'd do this:
[1,2,3].
map(function(x){return x*2}).
reduce(function(x,y){return x+y},0);
Conceptually, functional style makes it look like you're applying filters to the array instead of iterating through the array. If you've ever used command line tools like grep then you'd find this concept very familiar.
Notice that we haven't introduced any variable assignments at all in the functional style.
The three core array methods/functions in the functional style are: map, reduce and filter. With them you can avoid something like 90% of for-loops.
Great question.
For an in-depth answer, check out this classic (and awesome) paper by John Hughes -- Why Functional Programming Matters.
First, Hughes explains what functional programming is not about, and cites some weak arguments that proponents of FP use. Good stuff (but too long to quote here).
Second, Hughes explains what FP is about:
It is now generally accepted that modular design is the key to successful programming, and recent languages such as Modula-II [6] and Ada [5] include features specifically designed to help improve modularity. However, there is a very important point that is often missed. When writing a modular program to solve a problem, one first divides the problem into subproblems, then solves the subproblems, and finally combines the solutions. The ways in which one can divide up the original problem depend directly on the ways in which one can glue solutions together. Therefore, to increase one’s ability to modularize a problem conceptually, one must provide new kinds of glue in the programming language. Complicated scope rules and provision for separate compilation help only with clerical details — they can never make a great contribution to modularization.
We shall argue in the remainder of this paper that functional languages provide two new, very important kinds of glue. We shall give some examples of programs that can be modularized in new ways and can thereby be simplified. This is the key to functional programming’s power — it allows improved modularization. It is also the goal for which functional programmers must strive — smaller and simpler and more general modules, glued together with the new glues we shall describe.
(emphasis mine)
So to get back to the original question, in order to do FP in Javascript, you'll want to build programs by implementing separate modules, then gluing them together. Javascript comes with some nice glue, and you can build even more glue on your own -- check out combinators.
You should try to avoid features that prevent you from using glue to combine modular pieces of code, for example:
mutable state -- especially if it's global
statements -- you can't pass while-loops as function arguments
some kinds of syntax, such as operators or property access -- you can't assign + to a variable or pass it as an argument
(These issues can, of course, be mitigated to a certain extent -- check out Javascript FP libraries for examples.)
On the other hand, features that aren't functions -- such as classes, objects, inheritance, prototypes, etc. -- don't necessarily stop you from using Javascript's glue, so there's no reason, from an FP standpoint, not to use them.

Categories