71

Is there a framework or post processor for JavaScript that supports lambda syntax like in C#?

Function definitions in CoffeeScript seem to look like lambdas but I have not looked into them thoroughly.

Can anyone tell me, can I use lambda syntax in JavaScript?

5
  • 6
    What do you mean ? Javascript has built-in lambdas. Commented Aug 25, 2011 at 12:39
  • 2
    working on it! github.com/elmerbulthuis/sjs Commented Apr 17, 2012 at 18:01
  • Yes, there are "lambda expressions" in JavaScript but they are called arrow function expression. See this link for more details Commented Apr 29, 2017 at 8:00
  • 4
    this is funny cos actually lambdas in c# and now Java have been actually inspired from javascript, not the other way around Commented May 24, 2017 at 12:27
  • @slaphappy did you mean function expressions when you said vanilla JavaScript has built-in lambdas? You use function expressions as lambda expression or something else. Commented Nov 2, 2017 at 6:17

6 Answers 6

74

Lambda functions with similar syntax are included in ECMAscript 6, they're known as "arrow functions". An example:

["duck", "cat", "goat"].filter(el => el.length > 3); returns ["duck", "goat"]

There's currently support in recent versions of Firefox and Chrome.

To use this syntax in JavaScript that's targeting older browsers there are tools that can compile ES 6 to a more widely supported version - for example the tools Babel or Traceur.

Sign up to request clarification or add additional context in comments.

4 Comments

I believe one can use Traceur to run it in any browser. github.com/google/traceur-compiler/wiki/GettingStarted
@stimpy77, Link is broken, should be: github.com/google/traceur-compiler/wiki/Getting-Started
If actually 'nothing' I think it would valuable if you explain why you think so. Thanks!
I think it's worth adding that you can use code blocks: array.filter(el => {console.log(el); return el.length>3;});
11

You could use typescript (www.typescriptlang.org/):

function (d, i) {
    return "translate(" + d.x + "," + d.y + ")";
}

would become

(d, i) =>  "translate(" + d.x + "," + d.y + ")"  

and much more cool stuff, like typing: ... that's if you are into that

3 Comments

This is now in Firefox nightly too, so seems a legit suggestion - people.mozilla.org/~jorendorff/es6-draft.html#sec-13.2
+1: I have been looking everywhere for info on ()=>{} etc in Javascript... I did not realise it was just a Typescript extension I had accidentally tripped over. Many thanks. :)
5

I started creating an extender for jQuery which does exactly the thing you are asking. JS-Lambda

For example in C#:

  coll.TakeWhile(x => x.index < 3);

Looks like:

 $(coll).TakeWhile("x => x.index < 3");

2 Comments

I know the lib isn't a fully functioning lib and i will never use it in a project, but it was just a fun hour project to get a lambda expression working in JavaScript.
Although it doesn't, without ES6 support, give you the lambda stuff, lodash or underscore are probably more complete/stable versions of what your library is trying to achieve. Might be worth taking inspiration from, at least.
3

Javascript has very nice anonymous functions that allows you to create lambdas anyWhere you need as a function but the implementation comes with some much words and scope creation repeating:

function(name){
     return "Hello, " + name;
}

Thanks to EcmaScript 2015 lambda expresion is now available for javaScript with simpler syntax as Arrow Function

(name) => "Hello, " + name

Comments

3

FIDDLE: https://jsfiddle.net/vktawbzg/

NPM: https://www.npmjs.com/package/linqscript

GITHUB: https://github.com/sevensc/linqscript

using Typescript i created a class List<T> which extends Array<T>

usage:

var list = new List<ListView>();
...
var selected = list.Items.Where(x => x.Selected);

implementation:

 export class List<T> extends Array<T> {

    public Where(callback: (value: T) => boolean, thisArg?: any): List<T> {
            try {
                const list = new List<T>();

                if (this.length <= 0)
                    return list;

                if (typeof callback !== "function")
                    throw new TypeError(callback + ' is not a function');

                for (let i = 0; i < this.length; i++) {
                    const c = this[i];
                    if (c === null)
                        continue;

                    if (callback.call(thisArg, c))
                        list.Add(c);
                }

                return list;
            }
            catch (ex) {
                return new List<T>();
            }
        }
...
}

EDIT: I created a github repo: https://github.com/sevensc/linqscript

2 Comments

Hi I'm trying to make the same, and specifically targetting the GroupBy method. do you have a link or any good resources?
Hi, yes of course, take a look at my github repo: github.com/sevensc/linqscript for some inspiration.
3

Exact Matthew Mcveigh!!

I want to contribute too, see this example

"use strict";
/* Lambda Helper to print  */
function PrintLineForElement(element, index, array){
  document.write("a[" + index + "] = " + JSON.stringify(element)+"<br>");
}
/* function to print array */
function Print(a){
   a.forEach(PrintLineForElement)
   document.write("<br>");
}
/* user model */
class User{
		constructor(_id,_name,_age,_job){
			 this.id = _id;
       this.name = _name;
			 this.age = _age;
       this.job = _job;
		}
} 
/* Provaider users */
class UserService{ 

		constructor(){ } 
    
		GetUsers(){
        //fake ajax response
				let data = [];	
        data.push(new User(1,"Juan",20,"AM"));
        data.push(new User(2,"Antonio",20,"AM"));
        data.push(new User(3,"Miguel Angel",30,"Developer"));
        data.push(new User(4,"Bea",26,"AM"));
        data.push(new User(5,"David",24,"Developer")); 
        data.push(new User(6,"Angel",24,"Developer")); 
        data.push(new User(7,"David",34,"TeamLead"));
        data.push(new User(8,"Robert",35,"TeamLead"));
        data.push(new User(9,"Carlos",35,"TeamLead"));   
				
        return data;
		}
}

const userService = new UserService();
const users =  userService.GetUsers();

//get user order by name
document.write("All users </br>");
Print(users);

//get user order by name
document.write("Order users by name ASC : users.sort((a,b)=>{return a.name > b.name })</br>");
Print(users.sort((a,b)=>{return a.name > b.name; }));
document.write("Order users by name DESC : users.sort((a,b)=>{return a.name < b.name })</br>");
Print(users.sort((a,b)=>{return a.name < b.name; }));

//get user filter by age 
document.write("Only users oldest or equal than 25 : users.filter( (w) => {return w.age >= 25;} )</br>");
Print(users.filter( (w) => {return w.age >= 25;} )); 
document.write("Only users smallest or equal than 25 : users.filter( (w) => {return w.age <= 25;} )</br>");
Print(users.filter( (w) => {return w.age <= 25;} )); 

//GroupBY 
/**
* custom group by with Array.prototype.keys
**/

Array.prototype.groupBy = function(f)
{
  let groups = [];
  this.forEach( function( o )
  {
    let group =  f(o) ;
    groups[group] = groups[group] || [];
    groups[group].push( o );  
  });

  return Object.keys(groups).map( function( group )
  {
    return groups[group]; 
  })
}

document.write("Group user by age </br>");
Print(users.groupBy( (w) => {return w.age } )); 

document.write("Group user by job </br>");
Print(users.groupBy( (w) => {return w.job } )); 

document.write("Group user by job</br>");
Print(users.groupBy( (g) => {return [g.job] } ));

document.write("Group user by job and age then order by name </br>");
Print(users.sort((a,b)=>{return a.job > b.job}).groupBy( (g) => {return [g.job+g.age] } ));

document.write("Group user by job and age then order by name and filter where age < 25 and job equal AM </br>");
Print(users.sort((a,b)=>{return a.job > b.job}).filter((w)=>{ return w.age<25 || w.job == "AM" }).groupBy( (g) => {return [g.job+g.age] } ));

https://jsfiddle.net/angelfragap/0b5epjw3/29/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.