Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
Javascript fluent style - way to access entire array within call chain like "tap" in RXJS

After using RXJS, I have loved using tap operator which essentially allows you to peek into a chain without modifying it. I would love to do the same with a fluent array chain. This can be done by adding a function to the prototype as shown below, but is there a way to do the same or similar using standard array methods? Also, is there any developments on adding this to the specification (or rationale as to why not to have it)?

I know I could just break up the chain into multiple variables (i.e., const oddNumbers...) but that sometimes doesn't fit the style I am going for.

Array.prototype.tap = function(fn){
  const arr = Object(this)
  fn(arr);
  return arr
}

const numbers = [0,1,2,3,4,5];

const sumOfOdds = numbers.filter(x=>x%2)
                         .tap(oddNumbers => console.log(oddNumbers))
                         .reduce((acc,cur)=>acc+cur,0)
console.log(sumOfOdds);

One way to do this using map would be the following, but it is called n times and is not super pretty.

Array.prototype.tap = function(fn){
  const arr = Object(this)
  fn(arr);
  return arr
}

const numbers = [0,1,2,3,4,5];

const sumOfOdds = numbers.filter(x=>x%2)
                         .map((val, i, arr) => {
                            if (i === 0) // run once
                              console.log(arr);
                            return val; 
                         })
                         .reduce((acc,cur)=>acc+cur,0)
console.log(sumOfOdds);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

A .map which calls the other function inside the callback can do the same thing.

const numbers = [0,1,2,3,4,5];

const fn = oddNumber => console.log(oddNumber);
const sumOfOdds = numbers.filter(x=>x%2)
                         .map(num => (fn(num), num))
                         .reduce((acc,cur)=>acc+cur,0)
console.log(sumOfOdds);

or if you don't like the comma operator

const numbers = [0,1,2,3,4,5];

const fn = oddNumber => console.log(oddNumber);
const sumOfOdds = numbers.filter(x=>x%2)
                         .map(num => { fn(num); return num; })
                         .reduce((acc,cur)=>acc+cur,0)
console.log(sumOfOdds);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!