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!