#!/usr/bin/env node; /****************************************************************************** * This program compares recursion to iteration in computing palindromes. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ const Utils = require('./Utils'); const TEST_CASES = ["Hannah", "Able was I ere I saw Elba", "A man, a plan, a canal – Panama", "T. Eliot, top bard, notes putrid tang emanating, is sad; I'd assign it a name: gnat dirt upset on drab pot toilet.", "This is not a palindrome!"]; function palindromeRecursive0(s) { const S_LEN = Utils.cpLength(s); if (S_LEN < 2) { return true; } if (Utils.cpAt(s, 0) !== Utils.cpAt(s, S_LEN - 1)) { return false; } return palindromeRecursive0(Utils.cpSubstr(s, 1, (S_LEN - 1) - 1)); } function palindromeRecursive(s) { let s0 = s.replaceAll(/\W+/g, ""); s0 = s0.toLowerCase(); return palindromeRecursive0(s0); } function palindromeIterative(s) { let s0 = s.replaceAll(/\W+/g, ""); s0 = s0.toLowerCase(); const S_LEN = Utils.cpLength(s0); for (let x = 0; x <= Math.trunc((S_LEN - 1) / 2); ++x) { if (Utils.cpAt(s0, x) !== Utils.cpAt(s0, S_LEN - 1 - x)) { return false; } } return true; } const main = async () => { for (let s of TEST_CASES) { console.log(["Test Case: ", s].join('')); let result = palindromeRecursive(s); console.log(["palindromeRecursive: ", (result ? "Yes" : "No")].join('')); result = palindromeIterative(s); console.log(["palindromeIterative: ", (result ? "Yes" : "No")].join('')); } } main().catch( e => { console.error(e) } );