/**
* @file Defines a filter for formatting reference titles
* @author Reuben L. Lillie <reubenlillie@gmail.com>
*/
/**
* Format a title according to the _Chicago Manual of Style_
* @param {string} title A title to format
* @return {string} A formatted title
* @see Turabian 2018, 19.1.3 and 19.2.3
*/
export default title => {
/**
* Matches all letters in the English alphabet and all Arabic numerals
* @type {Object.<RegExp>}
*/
var RE_LETTER_OR_NUMBER = /(?<letterOrNumber>[a-zA-Z0-9])/giu
/**
* Matches opening and closing single and double quotes
* @type {Object.<RegExp>}
*/
var RE_QUOTES = /(?<quotes>[‘’“”'"])/giu
/**
* Matches double quotes
* @type {Object.<RegExp>}
*/
var RE_DOUBLE_QUOTES = /(?<doubleQuotes>[“”"])/giu
/**
* Matches open double quotes
* @type {Object.<RegExp>}
*/
var RE_OPEN_DOUBLE_QUOTES = /(?<openDoubleQuotes>[“"])/giu
/**
* Matches closing double quotes
* @type {Object.<RegExp>}
*/
var RE_CLOSE_DOUBLE_QUOTES = /(?<openDoubleQuotes>[”"])/giu
/**
* The `title`, except for the last character
* @type {string}
*/
var titleBeforeLastChar = title.slice(0, -1)
/**
* The last character of the `title`
* @type {string}
*/
var titleLastChar = title.slice(-1)
/**
* Use the unaltered `title`
* @string
*/
var formatted = title
// Is the last character of the `title` not a letter or number?
if(RE_LETTER_OR_NUMBER.test(titleLastChar)) {
// Then add a period
formatted = `${title}.`
}
// Is the last character a quotation mark of some kind?
if(RE_QUOTES.test(titleLastChar)) {
// Are they double quotes?
formatted = RE_DOUBLE_QUOTES.test(titleLastChar)
// Convert the double quotes to single quotes and add a period inside the last one
? `${titleBeforeLastChar
.replace(RE_OPEN_DOUBLE_QUOTES, '‘')
.replace(RE_CLOSE_DOUBLE_QUOTES, '’')}.’`
// Add a period inside the closing single quote
:`${titleBeforeLastChar}.${titleLastChar}`
}
return formatted
}