Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created January 13, 2012 21:32
Show Gist options
  • Save rwaldron/1608810 to your computer and use it in GitHub Desktop.
Save rwaldron/1608810 to your computer and use it in GitHub Desktop.
// JS Today
function List() {
this.list = [].slice.call(arguments);
}
List.prototype.diff = function( array ) {
return array.filter(function(item) {
return !~this.list.indexOf(item);
}, this);
};
var a = new List(1, 2, 3, 4, 5, 6);
a.diff([ 0, 2, 4, 6, 8, 10 ]);
// [ 0, 8, 10 ]
// Block Lambda and Rest Params
function List( ...args ) {
this.list = args;
}
List.prototype.diff = function( array ) {
return array.filter({ |item|
!~this.list.indexOf(item);
});
};
@indexzero
Copy link

So in the block lambda revival this has the same meaning as the outer function?

@rwaldron
Copy link
Author

Yes, the scope inside the block lambda is set to the scope of the LexicalEnvironment where it is running - which is awesome for avoiding var that = this; and .bind(this);

@rwaldron
Copy link
Author

Also, +9001 for being identifiable (the pipes look weird at first, but they've grown on me in their ability to clearly illustrate what this syntax is doing) and for being way less keystrokes to get the job done

@indexzero
Copy link

I don't like the implicit return, but besides that it's neat.

@rwaldron
Copy link
Author

Well, maybe this should be updated to include an example, but you can use an explicit return as well.

@ryanflorence
Copy link

Why the () around it? Why not

List.prototype.diff = function( array ) {
  return array.filter { |item|
    !~this.list.indexOf(item);
  };
};

@indexzero
Copy link

Think about this

List.prototype.diff = function( array ) {
  return array.filter { |item|
    !~this.list.indexOf(item);
  }.sort { |a, b| 
    // Do something with a and b
  };
};

I'm not a fan of }.

@davidflanagan
Copy link

Rick,

Note that you don't need the bind() call in ES5. The 2nd argument to filter() becomes the this value in the predicate.
I still want blocks, though!

@grayrest
Copy link

Why the () around it?

In that case JS either gets implicit parens for function calls or block lambda becomes a special case you have to explain to every new js developer.

@rwaldron
Copy link
Author

@david, ya know... I knew that and completely forgot thank you for pointing it out. I will update asap.

@rwaldron
Copy link
Author

@ryan that only flies if paren-free makes the cut. I meant to be conservative about what is being illustrated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment