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) // [πŸ‹, πŸ‹, πŸ₯, πŸ₯, πŸ₯]

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) // [πŸ‹, πŸ‹, πŸ₯, πŸ₯, πŸ₯]

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[]
  }
}

Now you can easily print each chain method result.

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

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 :heart: it if it’s help! Hope your enjoy.