Array.filter vs $filter('filter') - javascript

Which one should i use in an angular app and why?
array.filter(o => o.name === myName);
or
$filter('filter')(array, {name: myName}, true);

The key difference is the shortcuts or syntactic sugar provided by the $filter('filter'). For example, the following syntax can be used to get the items containing the keyword string in any of the item's string properties:
$filter('filter')(array, 'keyword')
Which can not be as simple using the standard ES5 Array.prototype.filter.
Whereas the general idea is the same for both approaches - to return a subset of a given array as a NEW array.
Update:
Under the hood angular uses the Array.prototype.filter:
function filterFilter() {
// predicateFn is created here...
return Array.prototype.filter.call(array, predicateFn);
}
So, if you don't use the shortcuts - angular simply delegates the call to the standard filter.
To answer your question: use the one that lets you write less code. In your particular case it would be array.filter(o => o.name === myName);

While using $filter('filter') can be easier and more syntactically attractive, I can think of four good reasons to use Array.filter over $filter('filter')
Efficiency
While it is true that $filter('filter') uses Array.filter under the hood, it also uses other code, including deep comparisons, in addition to Array.filter. In most cases the speed difference is negligible, but in some use cases it can be substantial. When working with large data objects for example, I've found that using Array.filter makes a difference.
Angular 2+ does not support AngularJS-style filter
From the angular migration guide:
The built-in AngularJS filter and orderBy filters do not exist in
Angular, so you need to do the filtering and sorting yourself.
If there is any possibility that you may upgrade to Angular 2 or higher in the future, then using Array.filter will save you some migration migraines. Even if you don't plan on upgrading, clearly the Angular team didn't think the AngularJS filter was worth keeping, which leads me to think it's probably better to avoid it anyway.
Favor native code over library code
Libraries and frameworks like AngularJS are amazing tools; But if you have to choose between using vanilla javascript or using a library, and there isn't a good reason to use the library, you should always use the vanilla javascript. It is more universally understood, less dependent on 3rd party code, etc. There are a plethora of online articles arguing this point.
"$filter" inhibits type-checking in Typescript files
This one only applies if you use (or plan to use) Typescript. At the time of writing, the #types library for angularjs defines the return type of all $filter functions as any, which can lead to some serious type-checking problems if you aren't careful. By contrast, Array.filter always returns the expected array type.

You should use Array.filter and then assign the result. When you use $filter, it is re-applied at the end of every $digest cycle for all the bindings and that is performance intensive to watch for the values and update the results after every $digest cycle. Instead you should filter your result and assign it to your scope variable explicitly

Related

Whether to use [array].filter or _.filter

my project includes underscorejs as a dependency. Internally I need to do a lot of complex array operations which basically includes me mapping over or filtering or reducing an array. We have native map, filter, reduce methods on Array.prototype. But the same methods are also available in underscorejs.
Personally, it makes more sense for me to use the native methods as it feels more natural in place of a wrapped object like _(array).filter(function(){}) or maybe _.filter(array, function(){}).
Please suggest.
This is really an opinion based question. Lodash will give you better browser support and possibly better performance, while the native functions might be arguably more clear on what they are doing. The native functions also handle some edge cases with sparse arrays and such, which may or may not be relevant to you.
Whatever floats your boat.
Personally I'd go for consistency. If you are already using underscore or lodash for their functions that aren't natively implemented (like _.uniq or _.pick) I'd just keep using _.filter and whatnot too.
If you need quite some complex operation go for underscore with the _.chain()
So you can chain call like this :
_.chain(array).filter(function(){}).pluck('name').unique();
This sample will extract all unique name of the matched data in the filter.
Unlike native function, this library has been developped to be more easy to use and provide a good performance without having any problems with browser compatibility.

Why does Underscore.js define function aliases

Underscore.js defines aliases for functions like _.each (alias: forEach) and _.map (alias: collect) and I don't understand why.
I initially thought this was to avoid issues with browsers that didn't implement those functions natively, my thinking was that calling [].map() would throw an error in IE7 and 8 because they didn't implement it natively but found that there was no issue since Underscore already defines those.
Then I thought it could have something to do with conflicts with other JS libraries like Prototype that implement similarly named functions but then realised that having an alias doesn't actually make a difference in the case of _.map since prototype implements .map and .colelct and actually I'd been using prototype's implementation all along (eg. this.collection.collect(...)).
So far it doesn't seem to have made any difference and it hasn't created any issues but I'd really like to know why this is happening.
I guess the purpose of aliases is to make the library more familiar for programmers with different backgrounds (eg, collect and include are used in Ruby, fold in functional languages etc).
Also, aliases can improve readability in some cases, for example
list.select(...).reject(...)
"sounds" better than
list.filter(...).reject(...)
If you look at their documentation, you will find it pretty close to lodash library (http://lodash.com/), and jQuery's library, and also Backbone and Ruby (found in the home page).
My guess, is that both of them are made to do the same thing, one in Server (Lodash), other in Client (Underscore), and to use the same syntax, they have some methods aliases.
Also, adding some aliases is never good, since it decreases errors when writing in multiple languages.

js library to support various data structures? (like guava in java)

Coming from Java I really like the flexibility afforded by the rich collection of data structures provided by Guava. Is there a "guava-like" library in js or jquery?
Note: I heard about closure and it seems a bit heavy - anything simpler? (or is closure really what I need?)
Note 2: by "rich collection of data structures" I mean sorted maps and sets, multimaps (duplicate keys allowed) and multisets (sets with multiple entries allowed - seems strange but actually very useful!), etc.
If by "the rich collection of data structures" for JS you meant utility for operating on JavaScript Arrays and Objects and JavaScript itself, then I'd recommend Underscore.js:
Underscore is a utility-belt library for JavaScript that provides a
lot of the functional programming support. (...) Underscore provides
60-odd functions that support both the usual functional suspects: map,
select, invoke — as well as more specialized helpers: function
binding, javascript templating, deep equality testing, and so on. It
delegates to built-in functions, if present, so modern browsers will
use the native implementations of forEach, map, reduce, filter, every,
some and indexOf.
It also has Set-like functions like union, intersection and difference, type-checking functions isXXX (isArray etc.), function goodies and more stuff you'd write yourself without such a library.
Underscore has clean code, is well tested and quite popular these days, I use it on daily basis in JS projects.
EDIT after question edit:
I know Guava has multimaps, multiset etc. but they are all consequesnce of Java design and it's hard to write 1 to 1 implementation of these collections in JS. It's because Javascript has no:
static typing,
classes in Java sense, uses prototyping instead (see this answer),
interfaces (but has functions as first-class objects on the other hand),
easily defined object equality (var t1 = { test: 1 }, t2 = { test: 1 }; t1 === t2 is false)
so it's hard to write general-use Set implementation, not mentioning Multiset or Multimap. There are for example some Set implementations like Closure's one or this one, but they are not perfect - first modifies elements inserted into Set (!), the second is not a mainstream, well-tested project (and personally I've never used it so can't say more).
In Javascript you just do var multimap = { key: [ 1, 2, 3.0 ], key2: [ 4, 'test', { bla: null }, 1 ] } and because of language design you can't just do multimap.containsValue({ bla: null }). I mentioned underscore.js because it has 95% utility functions you'll ever with JS collections, that is Arrays and Objects. If you want more, just use Closure's structs, but the library itself it's quite big.
There is a now a lighter, faster alternative to Underscore.js: Lo-Dash (http://lodash.com/).
js-sdsl
A javascript standard data structure library which benchmark against C++ STL.
This library has strict time complexity guarantee and can be used with confidence.
The latest beta version includes iterator functions which can be used like iterator in c++.
Included data structures
Vector
Stack
Queue
LinkList
Deque
PriorityQueue
Set (using RBTree)
Map (using RBTree)
HashSet (for reference only)
HashMap (for reference only)
Usage
To help you have a better use, we provide this API document.

I want to stop using OOP in javascript and use delegation instead

After dabbling with javascript for a while, I became progressively convinced that OOP is not the right way to go, or at least, not extensively. Having two or three levels of inheritance is ok, but working full OOP like one would do in Java seems just not fitting.
The language supports compositing and delegation natively. I want to use just that. However, I am having trouble replicating certain benefits from OOP.
Namely:
How would I check if an object implements a certain behavior? I have thought of the following methods
Check if the object has a particular method. But this would mean standardizing method names and if the project is big, it can quickly become cumbersome, and lead to the java problem (object.hasMethod('emailRegexValidatorSimpleSuperLongNotConflictingMethodName')...It would just move the problem of OOP, not fix it. Furthermore, I could not find info on the performance of looking up if methods exist
Store each composited object in an array and check if the object contains the compositor. Something like: object.hasComposite(compositorClass)...But that's also not really elegant and is once again OOP, just not in the standard way.
Have each object have an "implements" array property, and leave the responsibility to the object to say if it implements a certain behavior, whether it is through composition or natively. Flexible and simple, but requires to remember a number of conventions. It is my preferred method until now, but I am still looking.
How would I initialize an object without repeating all the set-up for composited objects? For example, if I have an "textInput" class that uses a certain number of validators, which have to be initialized with variables, and a class "emailInput" which uses the exact same validators, it is cumbersome to repeat the code. And if the interface of the validators change, the code has to change in every class that uses them. How would I go about setting that easily? The API I am thinking of should be as simple as doing object.compositors('emailValidator','lengthValidator','...')
Is there any performance loss associated with having most of the functions that run in the app go through an apply()? Since I am going to be using delegation extensively, basic objects will most probably have almost no methods. All methods will be provided by the composited objects.
Any good resource? I have read countless posts about OOP vs delegation, and about the benefits of delegation, etc, but I can't find anything that would discuss "javascript delegation done right", in the scope of a large framework.
edit
Further explanations:
I don't have code yet, I have been working on a framework in pure OOP and I am getting stuck and in need of multiple inheritance. Thus, I decided to drop classes totally. So I am now merely at theoretical level and trying to make sense out of this.
"Compositing" might be the wrong word; I am referring to the composite pattern, very useful for tree-like structures. It's true that it is rare to have tree structures on the front end (well, save for the DOM of course), but I am developing for node.js
What I mean by "switching from OOP" is that I am going to part from defining classes, using the "new" operator, and so on; I intend to use anonymous objects and extend them with delegators. Example:
var a = {};
compositor.addDelegates(a,["validator", "accessManager", "databaseObject"]);
So a "class" would be a function with predefined delegators:
function getInputObject(type, validator){
var input = {};
compositor.addDelegates(input,[compositor,renderable("input"+type),"ajaxed"]);
if(validator){input.addDelegate(validator);}
return input;
}
Does that make sense?
1) How would I check if an object implements a certain behavior?
Most people don't bother with testing for method existance like this.
If you want to test for methods in order to branch and do different things if its found or not then you are probably doing something evil (this kind of instanceof is usually a code smell in OO code)
If you are just checking if an object implements an interface for error checking then it is not much better then not testing and letting an exception be thrown if the method is not found. I don't know anyone that routinely does this checking but I am sure someone out there is doing it...
2) How would I initialize an object without repeating all the set-up for composited objects?
If you wrap the inner object construction code in a function or class then I think you can avoid most of the repetition and coupling.
3) Is there any performance loss associated with having most of the functions that run in the app go through an apply()?
In my experience, I prefer to avoid dealing with this unless strictly necessary. this is fiddly, breaks inside callbacks (that I use extensively for iteration and async stuff) and it is very easy to forget to set it correctly. I try to use more traditional approaches to composition. For example:
Having each owned object be completely independent, without needing to look at its siblings or owner. This allows me to just call its methods directly and letting it be its own this.
Giving the owned objects a reference to their owner in the form of a property or as a parameter passed to their methods. This allows the composition units to access the owner without depending on having the this correctly set.
Using mixins, flattening the separate composition units in a single level. This has big name clash issues but allows everyone to see each other and share the same "this". Mixins also decouples the code from changes in the composition structure, since different composition divisions will still flatten to the same mixed object.
4) Any good resources?
I don't know, so tell me if you find one :)

Javascript wrapper that gives us Rubyish Javascript?

Are there any frameworks/wrapper out there that gives us rubyish javascript?
Instead of the usual for() {} loop gives us the object.each {} loop like in Ruby?
Since javascript could be used in web browsers I do want to use it for the server side too, but I do like ruby syntax far more.
The Prototype library, having been developed by guys very close to Ruby on Rails, has a very Ruby-ish feel. It uses Ruby lingo (like mixins); for instance, the Enumerable mixin (which Prototype mixes in to arrays by default) adds the each method to an array, so you can do this:
["sample", "array"].each(function (item) {
console.log(item);
});
look up jQuery. it has a
$('.css-selector').each(function(i){
//do stuff
});
Ref: http://api.jquery.com/jQuery.each/
You might want to checkout JS.Class - Ruby-style JavaScript. From the docs,
JS.Class is a set of tools designed to make it easy to build robust object-oriented programs in JavaScript. It’s based on Ruby, and gives you access to Ruby’s object, module and class systems, some of its reflection and metaprogramming facilities, and a few of the packages from its standard library. It also provides a powerful package manager to help load your applications as efficiently as possible.
It comes with a well packaged standard library including modules and classes such as
Enumerable
Hash
Set
Observable
Command
The Enumerable module, for instance, is comparable to that in Ruby, and includes methods like
all
any
collect
drop
findAll
forEach
grep
partition
reject
select
zip
Here's a post by Ken Egozi which discusses adding .forEach and other helpers to the array prototype.

Categories

Resources