Haskell infix operator for javascript

Is there an equivalent construct in Javascript. If not, how would you create it?

Here is a simple explanation of what the infix operator does in Haskell:

What does the infix operator do in Haskell?

0
source share
3 answers

JavaScript does not have a list type, but Array s.

You can use...

 var newArr = [val].concat(arr); 

Alternatively, you can use unshift() to add to the array, but it modifies the original.

JavaScript does not have an operator : operator overloads or methods that look like operators, so you cannot get the same syntax as Haskell.

+4
source

I saw that Leila Hamon is already linked to this article on emulating infix operators in JS .

But I thought an example might be useful to others.

Here's how you could hack Number and Boolean prototypes to handle seconded infix expressions like 4 < 5 < 10 .

You can expand this by adding more methods for more prototypes. This is a bit ugly, but can be useful in order to make queries less verbose.

 //Usage code (4) .gt (6) .gt (4) //false (100) .lt (200) .lt (400) . gt(0) . gt(-1)//true (100) [ '>' ] (50) [ '<' ] (20)//false //Setup Code (function(){ var lastVal = null; var nP = Number.prototype var bP = Boolean.prototype nP.gt = function(other){ lastVal = other; return this > other; } nP.lt = function(other){ lastVal = other; return this < other; } bP.gt = function(other){ var result = lastVal > other; lastVal = other; return result; } bP.lt = function(other){ var result = lastVal < other; lastVal = other; return result; } bP['<'] = bP.lt bP['>'] = bP.gt nP['<'] = nP.lt nP['>'] = nP.gt })() 
+2
source

It is not the most beautiful, but it can help with readability in those places where you want infix so that your code reads like prose

 function nfx(firstArg, fn, secondArg){ return fn(firstArg, secondArg); } // Usage function plus(firstArg, secondArg) { return firstArg + secondArg; } nfx(1, plus, 2); 
0
source

All Articles