I love lodash and I use it in many projects.
I always have this problem and I can't find a solution for it.
I would like to do something with lodash, save a temporary state, and continue.
For example lets assume I have moviesList which is a list of movies with their id and profit, and I want to
index movies by their id and keep the result in moviesById
filter profitable movies and keep the result in overMillionProfit
And I want to do so without breaking the chain.
Something like (wishful thinking):
var moviesList = [{id : 1}, {id:2}, ...];
var moviesById = {};
var overMillionProfit = [];
_(moviesList)
.keyBy('id')
.do((unwrappedValue)=> moviesById = unwrappedValue)
.values()
.filter( (m) => m.profit > 1000000)
.do((unwrappedValue) => overMillionProfit = unwrappedValue)
Currently, I find it necessary to break the chain like so:
var moviesList = [{id : 1}, {id:2}, ...];
var moviesById = _.keyBy(moviesList,'id');
var overMillionProfit = _.filter(moviesList, ...);
Perhaps for this scenario it is better, but I want to be able to do it like the above in some cases.
Is there a way to do this?
You can use _.tap() for that:
var moviesList = [{id : 1}, {id:2}, {id:3}];
var moviesById;
var overMillionProfit;
var result = _(moviesList)
.keyBy('id')
.tap((unwrappedValue)=> moviesById = unwrappedValue)
.values()
.filter( (m) => m.id > 1)
.tap((unwrappedValue) => overMillionProfit = unwrappedValue)
.value();
console.log('moviesById\n', moviesById);
console.log('overMillionProfit\n', overMillionProfit);
console.log('result\n', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Related
I have some code that determines if the player has bought something or not in the store. I want to give that player the item if any of the values == true
var store = {
'bought' : [false, false, false, false, false, false],
'purchased': 0,
}
i was trying something like if (store[bought[1]]) == true but i suck at coding so it doesnt work
So, you have a dictionary named store. And it has a 'bought' key that you can read, like this:
var bought = store['bought']
Or like this:
var bought = store.bought
And that key is associated with an array, that you can index, like this:
var bought = store['bought']
var item = bought[0]
Or like this:
var bought = store.bought
var item = bought[0]
Or, if you don't want to take bought in a separate variable, you should be able to access it like this:
var item = store['bought'][0]
Or like this:
var item = store.bought[0]
I want to convert my class to a Map so I'm using Serialization package. From the example it looks simple:
var address = new Address();
address.street = 'N 34th';
address.city = 'Seattle';
var serialization = new Serialization()
..addRuleFor(Address);
Map output = serialization.write(address);
I expect to see an output like {'street' : 'N 34th', 'city' : 'Seattle'} but instead it just output something I-don't-know-what-that-is
{"roots":[{"__Ref":true,"rule":3,"object":0}],"data":[[],[],[],[["Seattle","N 34th"]]],"rules":"{\"roots\":[{\"__Ref\":true,\"rule\":1,\"object\":0}],\"data\":[[],[[{\"__Ref\":true,\"rule\":4,\"object\":0},{\"__Ref\":true,\"rule\":3,\"object\":0},{\"__Ref\":true,\"rule\":5,\"object\":0},{\"__Ref\":true,\"rule\":6,\"object\":0}]],[[],[],[\"city\",\"street\"]],[[]],[[]],[[]],[[{\"__Ref\":true,\"rule\":2,\"object\":0},{\"__Ref\":true,\"rule\":2,\"object\":1},\"\",{\"__Ref\":true,\"rule\":2,\"object\":2},{\"__Ref\":true,\"rule\":7,\"object\":0}]],[\"Address\"]],\"rules\":null}"}
Serialization is not supposed to create human-readable output. Maybe JSON output is more what you look for:
import dart:convert;
{
var address = new Address();
..address.street = 'N 34th';
..address.city = 'Seattle';
var encoded = JSON.encode(address, mirrorJson);
}
Map mirrorJson(o) {
Map map = new Map();
InstanceMirror im = reflect(o);
ClassMirror cm = im.type;
var decls = cm.declarations.values.where((dm) => dm is VariableMirror);
decls.forEach((dm) {
var key = MirrorSystem.getName(dm.simpleName);
var val = im.getField(dm.simpleName).reflectee;
map[key] = val;
});
return map;
}
The new Address() creates a full prototype object which is what you are seeing. That being said, they could have done something to avoid part of those, but if you want to restore the object just the way it is, that's necessary.
To see the full content of an object you use the for() instruction in this way:
for(obj in idx) alert(obj[idx]);
You'll see that you get loads of data this way. Without the new Address() it would probably not be that bad.
Serialization won't help you here...
You might give a try to JsonObject library, and maybe go through this in depth explanation how to do what you are trying to do using mirrors.
I have scrollableViews with a id name like idname1, idname2, idname88 etc. I want to destroy all widgets with a id name starting with "idname".
I have tried this:
var widgets = dijit.findWidgets("id^=divNodes");
dojo.forEach(widgets, function(w) {
w.destroyRecursive(false);
It seems that I cant use dijit.findWidgets("id^=divNodes") for this.
What will work for this?
From the docs...
registry.findWidgets returns an array of all non-nested widgets inside
the given DOM node.
https://dojotoolkit.org/reference-guide/1.8/dijit/registry.html
You could iterate over the registry yourself
require(["dojo/_base/array", "dijit/registry"], function(array, registry){
var startsWith = function(wholeString, lookFor) {
return wholeString.slice(0, lookFor.length) == lookFor}
};
var toDestroy = array.filter(registry.toArray(),
function(w) { return startsWith(w.id, 'divNodes'); });
array.forEach(toDestroy, function(w) { w.destroyRecursive(false); });
});
I have a list which contains a dictionary of ExpandoObjects. Im binding this to a grid but now I want to sort the list.
var rows = new List<dynamic>();
for (int i = 0; i < 1000; i++)
{
dynamic expandy = new ExpandoObject();
var dictionary = (IDictionary<string, object>)expandy;
dictionary.Add("ID", i);
dictionary.Add("Name", "Name" + i);
rows.Add(dictionary);
}
So looking at the test code above how would I sort rows (ascending or decending) say on "ID" or "Name" or any other property that I dynamically add?
A bit more info, I'm looking to sort it like this (this doesnt work);
var newOrder = from r in rows
orderby ("Name") ascending
select r;
Not sure how I missed this but anyway this works,
var newOrder = rows.OrderByDescending(x => x["Name"]);
WooHoo's answer does not work for Dynamic.ExpandoObject; this works:
var newOrder = rows.OrderByDescending(x =>((IDictionary<string,object>)x)["Name"]);
Is there a lambda equivalent of IN? I will like to select all the funds with ids either 4, 5 or 6. One way of writing it is:
List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId == 5 || fhp.Fund.FundId == 6 || fhp.Fund.FundId == 7).ToList();
However, that quickly becomes unmanageable if I need it to match say 100 different fundIds. Can I do something like:
List
fundHistoricalPrices =
lionContext.FundHistoricalPrices.Where(fhp
=> fhp.Fund.FundId in(5,6,7)).ToList();
It's somewhere along these lines, but I can't quite agree with the approach you have taken. But this will do if you really want to do this:
.Where(fhp => new List<int>{5,6,7}.Contains( fhp.Fund.FundId )).ToList();
You may want to construct the List of ids before your LINQ query...
You can use the Contains() method on a collection to get the equivalent to in.
var fundIds = new [] { 5, 6, 7 };
var fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fundIds.Contains(fhp.Fund.FundId)).ToList();
You could write an extension method like this :
public static bool In<T>(this T source, params T[] list)
{
if(null==source) throw new ArgumentNullException("source");
return list.Contains(source);
}
Then :
List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId.In(5,6,7)).ToList();
No, the only similar operator i'm aware of is the Contains() function.
ANother was is to construct your query dynamically by using the predicate builder out of the LINQkit: http://www.albahari.com/nutshell/predicatebuilder.aspx
Example
int[] fundIds = new int[] { 5,6,7};
var predicate = PredicateBuilder.False<FundHistoricalPrice>();
foreach (int id in fundIds)
{
int tmp = id;
predicate = predicate.Or (fhp => fhp.Fund.FundId == tmp);
}
var query = lionContext.FundHistoricalPrices.Where (predicate);