expand_contractions.js (2514B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var objectKeys = require( '@stdlib/utils/keys' ); 24 var isCapitalized = require( '@stdlib/assert/is-capitalized' ); 25 var uncapitalize = require( '@stdlib/string/uncapitalize' ); 26 var capitalize = require( '@stdlib/string/capitalize' ); 27 var tokenize = require( './../../tokenize' ); 28 var isString = require( '@stdlib/assert/is-string' ).isPrimitive; 29 var CONTRACTIONS = require( './contractions.json' ); 30 31 32 // VARIABLES // 33 34 var KEYS = objectKeys( CONTRACTIONS ); 35 36 37 // MAIN // 38 39 /** 40 * Expands all contractions to their formal equivalents. 41 * 42 * @param {string} str - string to convert 43 * @throws {TypeError} must provide a primitive string 44 * @returns {string} string with expanded contractions 45 * 46 * @example 47 * var str = 'I won\'t be able to get y\'all out of this one.'; 48 * var out = expandContractions( str ); 49 * // returns 'I will not be able to get you all out of this one.' 50 * 51 * @example 52 * var str = 'It oughtn\'t to be my fault, because, you know, I didn\'t know'; 53 * var out = expandContractions( str ); 54 * // returns 'It ought not to be my fault, because, you know, I did not know' 55 */ 56 function expandContractions( str ) { 57 var tokens; 58 var token; 59 var out; 60 var key; 61 var i; 62 var j; 63 64 if ( !isString( str ) ) { 65 throw new TypeError( 'invalid argument. Must provide a primitive string. Value: `'+str+'`.' ); 66 } 67 out = ''; 68 tokens = tokenize( str, true ); 69 for ( i = 0; i < tokens.length; i++ ) { 70 token = tokens[ i ]; 71 if ( isCapitalized( token ) ) { 72 for ( j = 0; j < KEYS.length; j++ ) { 73 key = KEYS[ j ]; 74 if ( uncapitalize( token ) === key ) { 75 token = capitalize( CONTRACTIONS[ key ] ); 76 break; 77 } 78 } 79 } else { 80 for ( j = 0; j < KEYS.length; j++ ) { 81 key = KEYS[ j ]; 82 if ( token === key ) { 83 token = CONTRACTIONS[ key ]; 84 break; 85 } 86 } 87 } 88 out += token; 89 } 90 return out; 91 } 92 93 94 // EXPORTS // 95 96 module.exports = expandContractions;