Return true in an incorrect manner

Coderbyte Challenge 7

Need help with a function that checks if every letter in the string is bounded by '+' signs. The code provided seems to be returning incorrect results - it should return false for the input string below as 'k' is missing a right-hand side '+'. Any assistance would be appreciated.

str = '+f+++l+k=+'

alpha = 'abcdefghijklmnopqrstuvwxyz'
function SimpleSymbols(str) {
  str = str.toLowerCase()
  for (i=0 ; i<str.length ; i++)  {

    if (alpha.indexOf(str.charAt(i)) > 0 && i === 0)  {
        return false 
    }
    else if (alpha.indexOf(str.charAt(str.length -1)) > 0) {
        return false 
    }
     else  if (alpha.indexOf(str.charAt(i)) > 0 && 
        (str.charAt(i-1) !== '+' || str.charAt(i+1) != '+')) {
         return false
    }
     else {return true}    
   }       
}

Answer №1

If you break the for loop at the first iteration, your function will stop prematurely. Instead, only break the loop on the branches where the condition is false. After completing the for loop without encountering any false conditions, return true.

Answer №2

Here is another approach:

You can implement the following logic:

Find the count of alphabets and the count of alphabets enclosed in a + sign on both sides. If the two counts are equal, then return true, otherwise return false

function CheckSymbols(str) {
   return str.match(/[a-z]/gi).length == str.match(/\+[a-z]\+/g).length
}

Answer №3

What are your thoughts on this straightforward reasoning?

str = '+f+++l+k++'

function SimpleSymbols(str) {
  str = str.toLowerCase()
  for (i=0 ; i<str.length ; i++)  {
      if (str[i] === '+') {
          continue;
      }

      if (i === 0 || i === str.length - 1) {
          return false;
      }

      if (str[i - 1] === '+' && str[i].match(/[a-z]/) && str[i + 1] === '+') {
          i += 1;
          continue;
      } else {return false;}
  } 

  return true;
}

Fiddle

Answer №4

While the Regex solution is concise, opting for a version using string.split can greatly enhance readability:

function CheckSymbols(input){
     if(input.length === 0) return false;
     if(input[0] !== '+' || input[input.length-1] !== '+') return false;
     var sections = input.split('+');
     for(var j=0; j < sections.length; j++){
          if(sections.length > 1) return false;
     }
     return true;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to achieve a height transition using CSS instead of relying on JavaScript

I created these custom cards using a combination of HTML, CSS, and JavaScript. However, I've noticed that the height transition animation is not as smooth as I'd like it to be, especially on certain pages. Is there a way to achieve this animation ...

Executing a JavaScript function within Python using Selenium: A beginner's guide

Within my JavaScript, there is a function called 'checkdata(code)' which requires an argument named 'code' to execute and returns a 15-character string. I recently discovered how to call functions without arguments in JavaScript. Howev ...

What makes long polling to an asp.net mvc app necessitate using the POST instead of GET ajax method?

Currently, my team and I are working on replicating a demo app showcased by Steven Sanderson in his SignalR demonstration, specifically focusing on the long polling feature. While the demo is functioning properly, we have encountered an issue when switchin ...

Having difficulty generating a footer for a page that includes a Material-UI Drawer component

Looking to create a standard full-width footer at the bottom of my page, I need help with the implementation. Utilizing the "Permanent drawer" from Material-UI Drawer for reference here. If you're interested in experimenting with it, CodeSandbox link ...

Navigating through the year selection with your keyboard

By default, a dropdown menu containing years allows for keyboard navigation. For example, if you type in 1992 while the dropdown is selected, it will automatically move to that specific year option. I am curious to know if there is a way to activate a two ...

How can I compare the current page URL with the navigation bar?

Looking to compare the URL of a current page to an element in the navigation bar using jQuery. Started by assigning the current URL to a variable: var currentPage = window.location.href; Then utilized an .each function to loop through each item in the n ...

Utilizing ng For in a personalized directive to fill a selection menu

I encountered an issue while trying to populate a selected dropdown using ngRepeat inside a custom directive. I came across this example that seemed similar to what I wanted to achieve here. Although it worked for the example, it didn't work for me. ...

Creating a versatile structure for your codebase

Okay, here's the deal: I've got this algorithm with parameters A, B, C, and D, and operations X, Y, and Z. The challenge is to develop code that can test all possible combinations (within certain ranges) of A, B, C, and D, while also being able t ...

I am facing an issue with my Angular 11 CLI application while trying to set it up with Jest. The specific error message I am encountering is: "TypeError: Cannot read property

Having issues with my Angular 11 cli app and Jest integration. Whenever I run npm run test, specifically jest --updateSnapshot, I encounter the following error in my terminal: Error: TypeError: Cannot read property 'paths' of undefined Here is ...

My Node setup is not displaying my scene with the THREE.js Software Renderer

Struggling to incorporate 3d graphics into Node.js environment, I stumbled upon the Software Renderer after exhaustive research. The renderer is up and running, but I am facing difficulties in rendering my scene. The issue lies in the fact that my 3d obje ...

javascript, issues with floating and displaying elements

I am currently working on creating a JavaScript menu that has a click function to smoothly slide up and down. Although the JavaScript code appears to be functioning correctly, it seems that there is some interference with the CSS. Despite attempting vario ...

Looping through arrays within objects using NgFor in Angular 2/JavaScript

I have a custom object with data that I am iterating through using ngFor. Within this object, there is an array component that I also want to iterate through in a <li></li>. Currently, the output appears as one complete string within each < ...

React/MaterialUI - Is there a way to customize the placeholder text for my multi-input field beyond the provided options?

I have a dropdown menu that accepts two JSON objects, symbol and company. export default function SymbolInput() { const [data, setData] = useState({ companies: [] }); const classes = useStyles(); useEffect(() => { Axios.get(" ...

Tips for executing forEach on a promise?

I am currently working with a function that returns a promise of an array: async function functionReturningPromiseOfUserIDs(): Promise<string[]> My question is, can I use the forEach method on the array returned by this function? async function runF ...

Discovering the Longest Oscillating Subsequence's Length

I am attempting to create a straightforward recursive definition that identifies the length of the longest oscillating subsequence within an array. My approach involves examining both the X[i] and X[i-1] elements, comparing them, and updating a counter a ...

Methods to maintain the select2 dropdown event open while interacting with another select2 dropdown

I have a situation where I need to dynamically add a class to a div whenever a select2 dropdown is open. To achieve this functionality, I am utilizing the open and close events of select2. The current code successfully adds the class when opening a selec ...

MERN stack: HTML is currently processing while React is failing to compile

I can't seem to figure out why I'm not receiving an error message, but when trying to launch a react app with node, only the Html is being displayed. Am I overlooking something? I've attempted the <script type="text/babel" src=".. ...

Javascript: triggering a self-executing function manually

I have a code snippet similar to the following: var msg="first call"; (function test(msg) { console.log("inside self call"); } )(); msg="second call"; console.log("before inline call"); test(msg); console.log("after inline call"); In thi ...

Unchecked checkbox displays as checked in UI

I am facing an issue with checking checkboxes using JavaScript. Even though the checkbox appears to be checked in the program, it does not reflect the updates on the user interface. If anyone has a solution for this, please share. <!DOCTYPE html> ...

The chosen option does not equal the value retrieved by using jQuery's

I am perplexed by the situation at hand. It seems that there is a discrepancy in the selected option of my select element. Despite appearing as the empty default option on top, the inspected element reveals it displaying a value of 13. https://i.sstatic.n ...