UNPKG

algs4js

Version:

Basic algorithms and data structures implemented with es6

100 lines (84 loc) 3.23 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _LogUtil = require('../util/LogUtil'); var _LogUtil2 = _interopRequireDefault(_LogUtil); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Class SimpleStringAlgs * * Provides simple string algorithm functionality. */ var SimpleStringAlgs = function () { function SimpleStringAlgs() { _classCallCheck(this, SimpleStringAlgs); } _createClass(SimpleStringAlgs, null, [{ key: 'validate', value: function validate(str) { var isValid = typeof str === 'string' || str instanceof String; if (!isValid) { throw new Error('Input ' + str + ' was not a string primitive or String object.'); } } /** * Reverses a string using built-in JavaScript functionality. * * @param {string} The string to reverse * @return {string The reversed string} */ }, { key: 'reverseWithBuiltIns', value: function reverseWithBuiltIns(str) { this.validate(str); _LogUtil2.default.debug('Reversing string ' + str); var charArr = str.split(''); _LogUtil2.default.debug('Character array = ' + charArr); charArr.reverse(); _LogUtil2.default.debug('Reversed character array = ' + charArr); return charArr.join(''); } /** * Reverses a string without the use of built-in JavaScript functionality. * * @param {string} The string to reverse * @return {string The reversed string} */ }, { key: 'reverse', value: function reverse(str) { this.validate(str); _LogUtil2.default.debug('Reversing string ' + str); var revStr = ''; for (var i = str.length - 1; i >= 0; i--) { revStr += str.charAt(i); } return revStr; } /** * Checks for palindromes. * * Ignores non-word characters and the underscore * * @param {string} str, the string to Check. * @return {boolean} true if palindrome, false otherwise. */ }, { key: 'isPalindrome', value: function isPalindrome(str) { this.validate(str); var testStr = str.toLowerCase().replace(/\W/g, '').replace('_', ''); for (var i = 0; i < testStr.length / 2; i++) { if (testStr.charAt(i) !== testStr.charAt(testStr.length - 1 - i)) { return false; } } return true; } }]); return SimpleStringAlgs; }(); exports.default = SimpleStringAlgs;