Skip to content

Instantly share code, notes, and snippets.

@crutchcorn
Created January 29, 2020 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crutchcorn/788149cf8da6b84ca6dbc109cec3bc8e to your computer and use it in GitHub Desktop.
Save crutchcorn/788149cf8da6b84ca6dbc109cec3bc8e to your computer and use it in GitHub Desktop.
I got distracted during writing some code for a talk slide
const state = { test: 3, hello: 399, testinghhhh: 1 };
const stateWords = Object.keys(state);
const stateNumbers = Object.values(state);
const itemStr = 'Item';
const countStr = 'Count';
let longestWord = itemStr.length;
let longestNumber = countStr.length;
for (let word of stateWords) {
// Add one for the ` ` after the entry
longestWord = longestWord < word.length ? word.length : longestWord;
}
for (let number of stateNumbers) {
const numStr = `${number}`;
longestNumber = longestNumber < numStr.length ? numStr.length : longestNumber;
}
const getSpacing = (str, char, max) => {
const addedLength = max - str.length;
return char.repeat(addedLength);
}
const headerStr1 = `${itemStr}${getSpacing(itemStr, ' ', longestWord)}`;
const headerStr2 = `${countStr}${getSpacing(countStr, ' ', longestNumber)}`;
const headerStr = `${headerStr1} | ${headerStr2}`;
// Plus three because of the two spaces plus the `|`
const totalLength = headerStr.length;
const seperatorStr = getSpacing('', '-', totalLength);
const initialHeader = `${headerStr}\n${seperatorStr}\n`;
const tableString = stateWords.reduce((stateStr, word) => {
const numberOfInstances = `${state[word]}`;
const addedSpaceWord = getSpacing(word, ' ', longestWord);
const addedSpaceNumber = getSpacing(numberOfInstances, ' ', longestNumber);
return `${stateStr}${word}${addedSpaceWord} | ${addedSpaceNumber}${numberOfInstances}\n`;
}, initialHeader);
console.log('\n', tableString);
/** Should turn into:
Item | Count
-------------------
test | 3
hello | 399
testinghhhh | 1
* Yes I know that console.table exists, this is for something else
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment