user7898461
user7898461

Reputation:

Using map/filter behavior on Map instance

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?

Upvotes: 1

Views: 146

Answers (2)

FisNaN
FisNaN

Reputation: 2865

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());

Upvotes: 1

Bergi
Bergi

Reputation: 664326

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.

Upvotes: 1

Related Questions