Last active
November 16, 2023 17:29
-
-
Save jkohlin/c6685d2096b6fec15deaa3a16363d52f to your computer and use it in GitHub Desktop.
Create colorized console logs easier.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface ColorItem { | |
value: string | number | object | |
color?: string | |
} | |
type Input = (string | ColorItem)[] | |
/** | |
* Logs data to the console with customizable colors and formatting. | |
* @param {Input} data - An array of data to log. Each item can be a string, number, or object with a "value" property. | |
* Objects can also have a "color" property to specify a CSS color for the text. | |
* @returns {void} | |
* @example | |
* // Log a string and a purple number | |
* colorlog(['Hello, world!', { value: 42, color:'#cc66cc' }]) | |
* | |
* // Log an object with a custom color | |
* colorlog([{ value: 'Error:', color: 'red' },' Something went wrong.' ]) | |
*/ | |
function colorlog(data: Input): void { | |
// Placeholder arrays for format specifiers and arguments | |
let stringTemplate: string[] = [] | |
let args: (string | number | object)[] = [] | |
// Iterate through each piece of data | |
for (let item of data) { | |
if (typeof item === 'object' && 'value' in item) { | |
// Differentiate object by color property presence | |
if ('color' in item) { | |
stringTemplate.push('%c' + item.value) | |
args.push(`color: ${item.color}`) | |
stringTemplate.push('%c') // Reset color | |
args.push('color: inherit') | |
} else { | |
// Format based on type of value | |
switch (typeof item.value) { | |
case 'number': | |
if (Number.isInteger(item.value)) { | |
stringTemplate.push('%i') | |
} else { | |
stringTemplate.push('%f') | |
} | |
break | |
case 'string': | |
stringTemplate.push('%s') | |
break | |
case 'object': | |
stringTemplate.push('%o') | |
break | |
} | |
// Append item's value to args | |
args.push(item.value) | |
} | |
} else { | |
// Handle non-object items as strings | |
stringTemplate.push('%s') | |
args.push(item) | |
} | |
} | |
// Call console.log with format string and args | |
console.log(stringTemplate.join(''), ...args) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment