main.js (2433B)
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 isString = require( '@stdlib/assert/is-string' ).isPrimitive; 24 var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; 25 var prevGraphemeClusterBreak = require( './../../prev-grapheme-cluster-break' ); 26 var format = require( './../../format' ); 27 28 29 // MAIN // 30 31 /** 32 * Removes the last character(s) of a string. 33 * 34 * @param {string} str - input string 35 * @param {NonNegativeInteger} [n=1] - number of character to remove 36 * @throws {TypeError} must provide a string primitive 37 * @throws {TypeError} second argument must be a nonnegative integer 38 * @returns {string} updated string 39 * 40 * @example 41 * var out = removeLast( 'last man standing' ); 42 * // returns 'last man standin' 43 * 44 * @example 45 * var out = removeLast( 'presidential election' ); 46 * // returns 'presidential electio' 47 * 48 * @example 49 * var out = removeLast( 'javaScript' ); 50 * // returns 'javaScrip' 51 * 52 * @example 53 * var out = removeLast( 'Hidden Treasures' ); 54 * // returns 'Hidden Treasure' 55 * 56 * @example 57 * var out = removeLast( 'leader', 2 ); 58 * // returns 'lead' 59 */ 60 function removeLast( str, n ) { 61 var i; 62 63 if ( !isString( str ) ) { 64 throw new TypeError( format( 'invalid argument. First argument must be a string. Value: `%s`.', str ) ); 65 } 66 if ( str === '' ) { 67 return ''; 68 } 69 if ( arguments.length > 1 ) { 70 if ( !isNonNegativeInteger( n ) ) { 71 throw new TypeError( format( 'invalid argument. Second argument must be a nonnegative integer. Value: `%s`.', n ) ); 72 } 73 if ( n === 0 ) { 74 return str; 75 } 76 i = str.length - 1; 77 while ( n > 0 ) { 78 i = prevGraphemeClusterBreak( str, i ); 79 n -= 1; 80 } 81 return str.substring( 0, i + 1 ); 82 } 83 return str.substring( 0, prevGraphemeClusterBreak( str, str.length-1 ) + 1 ); // eslint-disable-line max-len 84 } 85 86 87 // EXPORTS // 88 89 module.exports = removeLast;