All files acronym.js

100% Statements 35/35
100% Branches 21/21
100% Functions 11/11
100% Lines 31/31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 901x 1x 1x 1x           1x       1x 1x 1x 1x     1x 1x       26x       2634x           252x         252x   193x 59x   49x 104x 101x   3x       10x         294x   294x             186x   108x           967x 967x       497x     294x         1x    
import words from 'more-words'
import capitalize from 'lodash.capitalize'
import lowercase from 'lodash.lowercase'
import defaults from 'lodash.defaults'
 
 
// Dictionary of words
// This is indexed by first letter.
// dictionary.a = [ 'apricots', 'always', ...]
const dictionary = {}
 
 
// Helper Functions
const isString = (text) => typeof text === 'string'
const isArray = (text) => text instanceof Array
const getWord = (letter) => (isAlpha(letter) ? (dictionary[letter][Math.floor(Math.random() * dictionary[letter].length)]) : letter)
const isAlpha = (letter) => /^[a-zA-Z]+$/g.test(letter)
 
// Set up the dictionary of words using word-list
function initialize () {
	const alphabet = 'abcdefghijklmnopqrstuvwxyz'
 
	// Empty array for each letter
	for (let i = 0; i < alphabet.length; i++)
		dictionary[alphabet.charAt(i)] = []
 
	// Put all the words into the right spot.
	for (let i = 0; i < words.length; i++)
		dictionary[words[i].charAt(0)].push(words[i])
}
 
 
// Main function
function acronym (text, options) {
	var actual = defaults(options || {}, {
		capitalize: true,
		separator: ' '
	})
 
	if (isString(text)) {
		// Return acronym for this word
		return processWord(text, actual)
	} else if (isArray(text)) {
		// Return acronym for each word in the array.
		return text.map((el) => {
			if (isString(el))
				return processWord(el, actual)
			else
				return undefined
		})
	} else {
		// ???
		return undefined
	}
}
 
 
function processWord (text, options) {
	// Split word into array of characters
	let arr = text.split('')
 
	// Transform each character into a whole word
	arr = arr.map((letter) => getWord(letter.toLowerCase()))
 
	// Correctly capitalize
	if (options.capitalize)
		arr = arr.map((word) => isAlpha(word) ? capitalize(word) : word)
	else
		arr = arr.map((word) => isAlpha(word) ? lowercase(word) : word)
 
	// Re-join using separator, but only join adjacent words.
	// Otherwise, spit out cahracters verbatim
	let result = ''
 
	for (let i = 0; i < arr.length; i++) {
		result += arr[i]
 
		// Add separator?
		if (i !== arr.length - 1 && (isAlpha(arr[i]) || isAlpha(arr[i + 1])))
			result += options.separator
	}
 
	return result
}
 
 
// Exports
initialize()
export default acronym