1

I have this Express route:

app.use('/stop_jobs', function (req, res, next) {

  const jobId = req.query && req.query.job_id;

  const stopped : Array<any> = [];

  for (let j of runningJobs.keys()) {
     if(j.id === jobId){
       stopped.push(j.stopThisInstance());
     }
  }

  res.json({success: {stopped}});

});

where

 const runningJobs = new Map<CDTChronBase,CDTChronBase>();

(CDTChronBase is a class)

the above works, but I'd like to simplify it if possible, something like this:

app.use('/stop_jobs', function (req, res, next) {
  const jobId = req.query && req.query.job_id;

  const stopped = runningJobs.keys().filter(j => {
     return j.id === jobId;
  })
  .map(v => {
     return j.stopThisInstance()
  });

  res.json({success: {stopped}});

});

but for the life of me, I cannot figure out how to get an Array instance of any of the methods on Map. Is there a way to use map/filter type methods on Map objects?

2 Answers2

1

I think you're looking for

const stopped = Array.from(runningJobs.keys())
  .filter(j => j.id === jobId)
  .map(j => j.stopThisInstance());

Apart from that, you could also use filter and map functions that work on iterators such as the .keys() of a Map.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Since the key and value are same object, you can extract one of them and then covert it into an array.
If you convert map into array directly, it will be in [[key, value],[key, value], ...] structure. Then pick index 0:

const stopped = Array.from(runningJobs)
  .map(job => job[0])
  .filter(key => key.id === jobId)
  .map(key => key.topThisInstance());
FisNaN
  • 2,517
  • 2
  • 24
  • 39
  • Key and value are of the same type, but they're not necessarily the same object. If they were, a `Set` should be used not a `Map`. – Bergi Mar 26 '18 at 23:58
  • @Bergi Yeah. I got exactly same answer as yours when I try to test it :( – FisNaN Mar 27 '18 at 00:00