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!