Say I've object like that:
const Companies = {Mazda : {revenue:50000, employees:1000},
Honda: {revenue: 102324, employees:2031}}
And this function:
const totalRevenue = (companies) =>
Object.values(companies)
.map(companyObject => companyObject.revenue)
.reduce((total, companyRevenue)=> total + companyRevenue)
How do I use JSDoc to tell the function
totalRevenue that the companies object is an object that every key it has, has a value of the kind {revenue: Number, employees: Number}
I'm specifically interested in something that WebStorm will understand.
You can describe every key in object with the {Object.<string, number>} notation. see more syntax examples here: http://usejsdoc.org/tags-type.html
for your specific scenario:
/**
* #param {Object.<string, {revenue: number, employees: number}>} companies
*/
const totalRevenue = (companies) =>
Object.values(companies)
.map(companyObject => companyObject.revenue)
.reduce((total, companyRevenue)=> total + companyRevenue)
Related
When having a map reduce I would like to also include the first value of user current balance and last value of user balnce ordered by the date
from r in results
group r by new {r.Date, r.UserId} into g
select new
{
Date = g.Key.Date,
UserId = g.Key.UserId,
Count = g.Sum(x => x.Count),
** StartBalance = g.First(x=>x.Balance),
EndBalance = g.Last(x => x.Balance)**
}
I am expecting to get the first balance of the user when he just logged in to the game and also the last balance of the same player of the user at the end of the day.
Is this something possible?
This should work:
g.OrderyBy(x => x.Date).Select(x => x.Balance).FirstOrDefault()
I am having two lists and I need to find sum of nested list and there should be filter on the first list.
Ex:
Class Customer{
string Name
List<Order> Orders
string State
}
Class Order{
int OrderID
int OrderTotal
int ItemCode
}
I need to find sum of Orders in a particular state, I am looking for a lambda expression for this.
Below is the lambda expression with can be used to get the sum of the orderTotal with the filter on state.
Customer customer = new Customer();
Now add some data to your customer object and Order object.
customer.Where(cust => cust.State.Equals("Alaska")).Sum(order => order.OrderTotal);
I have a function in Symfony3 with Doctrine2 which is searching for the nearest partner, using latitude and longitude:
public function findNearestPartner($lat,$lng) {
$rsm=new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('AppBundle\Entity\Partner','p');
$sqlQuery="SELECT p.*, (6371 * acos(cos(radians(:lat)) * cos(radians(p.latitude)) * cos(radians(p.longitude) - radians(:lng)) + sin(radians(:lat)) * sin(radians(p.latitude)))) AS distance
FROM sp_partner p
ORDER BY distance ASC
LIMIT 0,1";
$query=$this->_em
->createNativeQuery($sqlQuery,$rsm)
->setParameter('lat',$lat)
->setParameter('lng',$lng)
;
return $query->getOneOrNullResult();
}
As you see, I get the nearest Partner-Entity back - but there is also the field "distance", which I don't get back (but it would be very useful). Is there any way to get the value of this field?
I read in the docu (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html), but I can't find anything useful for this case.
You can make it through addScalarResult.
$rsm=new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('AppBundle\Entity\Partner','p');
$rsm->addScalarResult('distance', 'distance');
the result will be
array:2 [▼
0 => Partner{...},
distance => xxx
]
Please see I want list employee objects. So I have below two options.
List<Tuple<int, string, string, string>>
List<Employee>where Employee is class contains 4 properties.
My doubt is what should I use(tuple or list of employee object?
If it is List<Employee> then in which scenario I should use List<Tuple<int, string, ...>>.
You should not use tuples unless you are doing some sort of arithmetic operation where tuple would be an acceptable and widely understood method of supplying values. Tuples make it a maintenance nightmare for anyone who is not familiar with your process as you built it.
Edit: Think about the difference between seeing:
var employeeList = DAL.getEmployees();
var activeEmployees = employeeList.Where(employee => employee.IsActive);
vs
var employeeTuple = DAL.getEmployees();
var activeEmployees = employeeTuple.Where(employee => employee.Item3);
In the second example, I know THAT you created an active employee list, but I don't know HOW you did it.
That's rather obvious. If you already have the Employee class then using List<Employee> is straightforward:
List<Employee> list = new List<Employee>();
list.Add( e );
...
Employee e = list.Where( i => i.Name == "John" ).FirstOrDefault();
whereas using List<Tuple<...>> is at least cumbersome:
List<Tuple<....>> list = new List<Tuple<....>>();
list.Add( new Tuple<...>( e.Name, e.Surname, e.Whateverelse, e.YetAnother ) );
...
// retrieve the tuple
var tuple = list.Where( i => i.Item1 == "John" );
// make Employee out of it
Employee e = new Employee( e.Item1, e.Item2, e.Item3, e.Item4 );
I have a sorting problem in Scala that I could certainly solve with brute-force, but I'm hopeful there is a more clever/elegant solution available. Suppose I have a list of strings in no particular order:
val keys = List("john", "jill", "ganesh", "wei", "bruce", "123", "Pantera")
Then at random, I receive the values for these keys at random (full-disclosure, I'm experiencing this problem in an akka actor, so events are not in order):
def receive:Receive = {
case Value(key, otherStuff) => // key is an element in keys ...
And I want to store these results in a List where the Value objects appear in the same order as their key fields in the keys list. For instance, I may have this list after receiving the first two Value messages:
List(Value("ganesh", stuff1), Value("bruce", stuff2))
ganesh appears before bruce merely because he appears earlier in the keys list. Once the third message is received, I should insert it into this list in the correct location per the ordering established by keys. For instance, on receiving wei I should insert him into the middle:
List(Value("ganesh", stuff1), Value("wei", stuff3), Value("bruce", stuff2))
At any point during this process, my list may be incomplete but in the expected order. Since the keys are redundant with my Value data, I throw them away once the list of values is complete.
Show me what you've got!
I assume you want no worse than O(n log n) performance. So:
val order = keys.zipWithIndex.toMap
var part = collection.immutable.TreeSet.empty[Value](
math.Ordering.by(v => order(v.key))
)
Then you just add your items.
scala> part = part + Value("ganesh", 0.1)
part: scala.collection.immutable.TreeSet[Value] =
TreeSet(Value(ganesh,0.1))
scala> part = part + Value("bruce", 0.2)
part: scala.collection.immutable.TreeSet[Value] =
TreeSet(Value(ganesh,0.1), Value(bruce,0.2))
scala> part = part + Value("wei", 0.3)
part: scala.collection.immutable.TreeSet[Value] =
TreeSet(Value(ganesh,0.1), Value(wei,0.3), Value(bruce,0.2))
When you're done, you can .toList it. While you're building it, you probably don't want to, since updating a list in random order so that it is in a desired sorted order is an obligatory O(n^2) cost.
Edit: with your example of seven items, my solution takes about 1/3 the time of Jean-Philippe's. For 25 items, it's 1/10th the time. 1/30th for 200 (which is the difference between 6 ms and 0.2 ms on my machine).
If you can use a ListMap instead of a list of tuples to store values while they're gathered, this could work. ListMap preserves insertion order.
class MyActor(keys: List[String]) extends Actor {
def initial(values: ListMap[String, Option[Value]]): Receive = {
case v # Value(key, otherStuff) =>
if(values.forall(_._2.isDefined))
context.become(valuesReceived(values.updated(key, Some(v)).collect { case (_, Some(v)) => v))
else
context.become(initial(keys, values.updated(key, Some(v))))
}
def valuesReceived(values: Seq[Value]): Receive = { } // whatever you need
def receive = initial(keys.map { k => (k -> None) })
}
(warning: not compiled)