DEV Community

Edwin Wong
Edwin Wong

Posted on

Array print()

How troublesome every time console.log to each array chain method result for debugging?

Let's see following code

const fruits = [🍌, 🍎, 🍎, 🍍, 🍌, πŸ₯, πŸ₯, πŸ₯]
const result = fruits
                     .filter(emoji => [πŸ₯, 🍌].includes(emoji))
                     .map(emoji => emoji === 🍌 ? πŸ‹ : emoji)

console.log(result) // [πŸ‹, πŸ‹, πŸ₯, πŸ₯, πŸ₯]
Enter fullscreen mode Exit fullscreen mode

Nothing wrong with the code, just when the result is not what you expect, often you will need to trace back and print out each chain method result to find out which part doing wrong.

You probably do this during debug

const fruits = [🍌, 🍎, 🍎, 🍍, 🍌, πŸ₯, πŸ₯, πŸ₯]
const getKiwiNBanana = fruits.filter(emoji => [πŸ₯, 🍌].includes(emoji))                    
console.log(getKiwiNBanana) // [🍌, 🍌, πŸ₯, πŸ₯, πŸ₯]
const result = getKiwiNBanana.map(emoji => emoji === 🍌 ? πŸ‹ : emoji)
console.log(result) // [πŸ‹, πŸ‹, πŸ₯, πŸ₯, πŸ₯]
Enter fullscreen mode Exit fullscreen mode

Ok~ you did but you write more code and it is not that elegant.

Array.print()

Add this code in your app root and global level. With this minor extend functionality of Array that allow you to print the result effortless and elegant. You might cautious about eslint error no-extend-native, but don't be so worry if you are not extend existing built-in method and you shouldn't do it!

Typescript

To support Typescript, add this following code in your root level.

declare global {
  interface Array<T> {
    print(): T[]
  }
}
Enter fullscreen mode Exit fullscreen mode

Now you can easily print each chain method result.

const fruits = [🍌, 🍎, 🍎, 🍍, 🍌, πŸ₯, πŸ₯, πŸ₯]
const result = fruits
                     .filter(emoji => [πŸ₯, 🍌].includes(emoji))
                     .print() // [🍌, 🍌, πŸ₯, πŸ₯, πŸ₯]
                     .map(emoji => emoji === 🍌 ? πŸ‹ : emoji)
                     .print() // [πŸ‹, πŸ‹, πŸ₯, πŸ₯, πŸ₯]
Enter fullscreen mode Exit fullscreen mode

Looks clean and neat!
statisfied-face

There are many thing you can do in the print function like prefix string so that easy for you to search and debug. Or maybe you want disable print in production mode. I will leave it to you to handle this.

Do ❀️ it if it's help! Hope your enjoy.

Top comments (2)

Collapse
 
fjones profile image
FJones

Worth noting that there's a lot of code that does extend prototypes - but for very specific purposes: Polyfills. Which is probably where a lot of people get the impression that extending native object prototypes is a perfectly normal thing to do.

Collapse
 
edwinwong90 profile image
Edwin Wong

Thank for sharing!