main.js (2214B)
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 lowercase = require( '@stdlib/string/lowercase' ); 24 var replace = require( '@stdlib/string/replace' ); 25 var isString = require( './../../is-string' ).isPrimitive; 26 27 28 // VARIABLES // 29 30 var RE_NON_ALPHANUMERIC = /[^a-z0-9]/g; 31 32 33 // FUNCTIONS // 34 35 /** 36 * Comparator function for sorting characters in ascending order. 37 * 38 * @private 39 * @param {string} a - character 40 * @param {string} b - character 41 * @returns {number} comparison value 42 */ 43 function ascending( a, b ) { 44 if ( a < b ) { 45 return -1; 46 } 47 if ( a === b ) { 48 return 0; 49 } 50 return 1; 51 } 52 53 54 // MAIN // 55 56 /** 57 * Tests if a value is an anagram. 58 * 59 * @param {string} str - comparison string 60 * @param {*} x - value to test 61 * @throws {TypeError} first argument must be a string primitive 62 * @returns {boolean} boolean indicating if a value is an anagram 63 * 64 * @example 65 * var bool = isAnagram( 'I am a weakish speller', 'William Shakespeare' ); 66 * // returns true 67 * 68 * @example 69 * var bool = isAnagram( 'bat', 'tabba' ); 70 * // returns false 71 */ 72 function isAnagram( str, x ) { 73 if ( !isString( str ) ) { 74 throw new TypeError( 'invalid argument. First argument must be a string primitive. Value: `' + str + '`.' ); 75 } 76 if ( !isString( x ) ) { 77 return false; 78 } 79 str = lowercase( str ); 80 str = replace( str, RE_NON_ALPHANUMERIC, '' ); 81 x = lowercase( x ); 82 x = replace( x, RE_NON_ALPHANUMERIC, '' ); 83 if ( str.length !== x.length ) { 84 return false; 85 } 86 str = str.split( '' ) 87 .sort( ascending ) 88 .join( '' ); 89 x = x.split( '' ) 90 .sort( ascending ) 91 .join( '' ); 92 return ( str === x ); 93 } 94 95 96 // EXPORTS // 97 98 module.exports = isAnagram;