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() // [π, π, π₯, π₯, π₯]
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)
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.
Thank for sharing!