Recursion functions seem to be not providing a return value

I wrote a recursive function that needs to return an object from an array of objects. Each object in the array includes a reference to a neighboring object, as shown below:

{
  id: 5,
  neighbors: {
    north: 1,
    east: 6,
    south: 9,
    west: 4
  }
}

This represents the square number 5 on a 4x4 board.

The function requires the array of all board squares, the ID of the current square, and a direction:

function findFarthestEmpty(board, id, direction) {
  let nextSquare = board[id].neighbors[direction]
  if (nextSquare === null) {
    console.log('return last square on board', board[id])
    return board[id]
  } else {
    findFarthestEmpty(board, nextSquare, direction)
  }
}
//Test a move.
console.log(typeof(findFarthestEmpty(board, 5, 'north')))

When running the function as shown above, the proper square object is logged on line 4, but the statement "undefined" is returned. Could I be confusing statements and expressions?

If you need the board array:

let board = [ { id: 0,
neighbors: { north: null, east: 1, south: 4, west: null },
meeple: null },
{ id: 1,
neighbors: { north: null, east: 2, south: 5, west: 0 },
meeple: null },
{ id: 2,
neighbors: { north: null, east: 3, south: 6, west: 1 },
meeple: null },
{ id: 3,
neighbors: { north: null, east: null, south: 7, west: 2 },
meeple: null },
{ id: 4,
neighbors: { north: 0, east: 5, south: 8, west: null },
meeple: null },
{ id: 5,
neighbors: { north: 1, east: 6, south: 9, west: 4 },
meeple: null },
{ id: 6,
neighbors: { north: 2, east: 7, south: 10, west: 5 },
meeple: null },
{ id: 7,
neighbors: { north: 3, east: null, south: 11, west: 6 },
meeple: null },
{ id: 8,
neighbors: { north: 4, east: 9, south: 12, west: null },
meeple: null },
{ id: 9,
neighbors: { north: 5, east: 10, south: 13, west: 8 },
meeple: null },
{ id: 10,
neighbors: { north: 6, east: 11, south: 14, west: 9 },
meeple: null },
{ id: 11,
neighbors: { north: 7, east: null, south: 15, west: 10 },
meeple: null },
{ id: 12,
neighbors: { north: 8, east: 13, south: null, west: null },
meeple: null },
{ id: 13,
neighbors: { north: 9, east: 14, south: null, west: 12 },
meeple: null },
{ id: 14,
neighbors: { north: 10, east: 15, south: null, west: 13 },
meeple: null },
{ id: 15,
neighbors: { north: 11, east: null, south: null, west: 14 },
meeple: null } ]

Answer №1

You are receiving undefined due to the following reason:

typeof(findFarthestEmpty(board, 5, 'north'))

Currently, the recursive function is not returning anything. When the base case is reached, it returns the id, but it only returns to the recursive statement. To resolve this, you should add a return statement to the recursive case, so that it also returns the answer:

else {
   return findFarthestEmpty(board, nextSquare, direction)
  }

Answer №2

The function will be returned on line 7 and it will perform as anticipated

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

"Material-UI enhanced React date picker for a modern and user-friendly

Currently, I am utilizing the Date picker feature from Material UI. The code snippet responsible for implementing it is as follows: import { DatePicker } from 'redux-form-material-ui'; <Field name="birthDate" ...

handlebars.js template to check the condition based on the last item in an array

I am currently utilizing handlebars.js as my templating engine and am interested in creating a conditional segment that will only display if it happens to be the final item within an array located in the templates configuration object. { columns: [{< ...

React Button Axios: A Primer for Complete Beginners

For the past few weeks, I've been using create-react-app and trying to modify the App.js file to include a button that executes an axios HTTP request when clicked. However, during my attempts, I keep running into errors like "unexpected token" in hand ...

Angular: Handling window resizing events in your application

To handle window resize events in a non-angular application, we typically use the following code: window.onresize = function(event) { console.log('changed'); }; However, in angular applications, it's not recommended to directly acc ...

Issue with AngularJS directive: Isolated scope preventing values from being inserted into template

After setting up the directive below: angular.module('news.directives', []) .directive('newsArticle', function($location, $timeout) { return { restrict: 'AE', replace: 'true&apo ...

What is the process of relocating JSON and JS code from within an HTML file to external files?

My goal is to separate JSON and JavaScript code from the HTML file by moving them into external files. The examples shown below were part of a test I conducted to verify that the data was being successfully imported. As I begin to include real data, the J ...

Activate text-entry fields after a button has been pressed on polymer 1.0

I am currently developing a project focused on creating a list of doctors using the Polymer 1.0 framework. Within the doctor-list, I have integrated a Vaadin grid called doctors-grid.html to display data sourced from a JSON file. Upon double-clicking on a ...

Calculate the total number of array elements within a multi-dimensional array that meet a specific criterion

I'm attempting to tally values from an array based on a specific element within the array. Here's an example using the following array: Array ( [0] => Array ( [user] => 53 [grade] => A ) ...

Using html data attributes to encode JSON data with strings

Looking for a way to pass data to JavaScript, I decided to create a template tag as shown below: from django.utils.safestring import mark_safe from django import template import json register = template.Library() @register.simple_tag def mydata(): r ...

Issue with JQuery .fadeToggle() function: Unexpected behavior causing automatic fade-out

$(document).on('click', '.tree label', function(e) { $(this).next('ul').fadeToggle(); e.stopPropagation(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul cl ...

Organize the strings by first sorting them alphabetically based on the first letter and then by length starting from the longest. Next, arrange the strings in ascending

After experimenting and seeking help on stackoverflow, I have managed to sort an array of objects based on the 'plate' key using the following function: sort(function(a, b) { return a.plate.toLowerCase() > b.plate.toLowerCase() ? a.pla ...

Injecting multiple instances of an abstract service in Angular can be achieved using the following techniques

I am fairly new to Angular and currently trying to make sense of the code written by a more experienced developer. Please excuse me if I'm not adhering to the standard communication practices and vocabulary. There is an abstract class called abstract ...

What could be the reason that a MUI component does not disappear when the display is set to none in the sx prop?

I'm attempting to construct a responsive side drawer using MUI's Drawer component in React, specifically leveraging MUI version 4.12.1. In the example provided on the mui.com website, they utilize the sx prop and pass an object with different di ...

invisible recaptcha with synchronous ajax

Hey, I'm trying to figure out a solution on how to obtain the token or a valid response from Recaptcha and then proceed with running the ajax call. Does anyone have any suggestions on how to achieve this in a synchronous manner? Here's the proce ...

Display a loading progress bar with jQuery AJAX as your single page website content loads

I am currently working on a simple web page layout that consists of a navigation bar at the top and a body wrapper. Whenever a user clicks on a link in the navigation bar, I use .load to load the content of the page into the wrapper div. $(this).ajaxStar ...

Align the center of table headers in JavaScript

I'm currently in the process of creating a table with the following code snippet: const table = document.createElement('table'); table.style.textAlign = 'center'; table.setAttribute('border', '2'); const thead ...

Is there a way to store the output image arrays in a designated folder on my computer using my Python code within a JupyterLab notebook?

Currently, I'm utilizing a for loop in my Jupyter Notebook Python code to convert a .png image into an array and incorporate regions. However, when the output consists of 5 arrays, I am unable to determine how to save them to a designated folder on my ...

What is the method for determining if a list is empty?

Question: What is the best way to check if a list is empty in Python? def CleanWhiteSpace(theDict): content=[] for key,value in theDict.items(): for d in value: if value != " ": content.append(d) ...

Combining multiple dictionaries into one single dictionary array using JavaScript

In my JavaScript code, I am working with an array that looks like this: arr = [{"class":"a"},{"sub_class":"b"},{"category":"c"},{"sub_category":"d"}] My goal is to transform t ...

Solving SEO issues with jQuery load()

I have developed a modal window that includes links, but unfortunately, search engine crawlers are unable to read and index those links. I am looking for a solution to make sure the crawler can index those links. I have noticed websites using AngularJS li ...