A guide on creating a Javascript leap year algorithm using Test-Driven Development techniques

Currently, I am working on crafting a leap year algorithm by utilizing a TDD suite. This marks my initial venture into the realm of TDD.

Displayed below is the code extracted from the spec file.

var Year = require('./leap');

describe('Leap year', function() {

  it('is quite uncommon', function() {
    var year = new Year(2015);
    expect(year.isLeap()).toBe(false);
  });

  it('is added every 4 years to balance approximately a day', function() {
    var year = new Year(2016);
    expect(year.isLeap()).toBe(true);
  });

  it('is omitted every 100 years to eliminate an additional day', function() {
    var year = new Year(1900);
    expect(year.isLeap()).toBe(false);
  });

  it('is reintroduced every 400 years to balance an additional day', function() {
    var year = new Year(2000);
    expect(year.isLeap()).toBe(true);
  });

Here's what I have come up with in the leap.js file up to this point

var leapYear = function() {};

leapYear.prototype.isLeap = function(year) {
  if (year % 4 != 0) {
    return true;
  }
}

module.exports = leapYear;

Despite my best efforts, I am encountering the following setbacks:

Failures:

1) Leap year is not very common Message: Expected true to be false. Stacktrace: Error: Expected true to be false. at null.

2) Leap year is skipped every 100 years to remove an extra day Message: Expected true to be false. Stacktrace: Error: Expected true to be false. at null.

Execution Time: 0.014 seconds 4 tests, 4 assertions, 2 failures, 0 skipped

Any suggestions or insights would be greatly appreciated!

Answer №1

To simplify, the code should look like this:

var leapYear = function(year) {this.year = year};

leapYear.prototype.isLeap = function() {
  return this.year % 4 == 0 && this.year % 100 != 0 || this.year % 400 == 0;
}

module.exports = leapYear;

If the year ends in 00 (meaning year % 100 == 0), then check if it can be divided by 400. Otherwise, check if it can be divided by 4.

Update:

Explanation:

Firstly, the code

  • The test case requires a year object that is constructed with an integer, so your leapYear 'class' should take in an integer during construction, and store it as a member variable.
  • The isLeap function does not take any arguments, so it should not take any arguments either. It uses the year provided during object construction.

Next, the logic

  • The first test case checks if a year is not divisible by 4, in which case it is not a leap year.
  • The second test case checks if a year can be divided by 4, indicating it is a leap year.
  • The third test case checks if a year can be divided by 4, but ends in 00 (every 100 years), making it not a leap year.
  • The fourth test case checks if a year can be divided by 4, ends in 00, and can be divided by 400, making it a leap year.

Combining these cases, we can conclude:

  1. A year that is not divisible by 4 is never a leap year.
  2. A year that can be divided by 400 must be a leap year.
  3. A year divisible by 4 is a leap year if it is not divisible by 100.

By testing these cases one by one, you can determine if a year is a leap year.

Answer №2

  • year % 4 != 0 during standard years (2013, 2014, 2015).
  • There is currently no code to handle the 100-year and 400-year exceptions.
  • UPDATE: According to charlieftl, using .toBe(false) will not meet the requirement.

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

The Next.js build version encounters an issue with 'auth' property being undefined and causes a failure

Our team has been happily working on a Next.js based website for the past few months. Everything was running smoothly without any major issues until yesterday when we encountered an error on the production version while using router.push: Cannot read prope ...

React Component Transitions with Slide-Up Effect

Recently, I've been experimenting with incorporating animations and transitions into my React.js projects. In the animated GIF provided below, you can see that when I close a Message component, it smoothly fades out. Once the fade out animation comple ...

Teaching sessions along with the implementation of functions

I've created a set of input fields with the class replaceInput. The idea is to have a simple function that clears the value when the user focuses on the field, and then returns it to 'X' if the field is empty on focus out. My query is, coul ...

Passing data from the server to the HTML page for manipulation

I need assistance in retrieving and manipulating the value stored in the variable $result[] from a PHP file to my HTML file for further processing. Can you provide guidance or reference code on how to return data from server side to client side? Here is a ...

Having difficulty applying parseFloat directly following a JSON Stringify operation

There's a specific line of code I'm working with that reads -- let longitude = JSON.stringify(place.lon); After calling alert(longitude), I receive the output "44.54321". However, my intention is to retrieve just the number itself, so I attempt ...

What is the best way to reduce the size of a Base64/Binary image in Angular6

I utilized the Ngx-Webcam tool to capture images from my camera. My goal is to obtain both high quality and low quality images from the camera. Although this library provides me with Base64 images, it offers an option to reduce the size using imageQuality ...

Hiding Div with JavaScript (Quick and Easy)

Hey there, I'm looking to make regStart and regPage alternate visibility based on a click event. I'm still getting the hang of JavaScript so any simple answers would be appreciated. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/x ...

Attempting to move elements into an array for storage in the local storage

Is there a way to properly add elements to an array and store it in localstorage? Here's the code snippet I've been working with: const handleSelectLayouts = (layout) => { const layoutsArray = []; layoutsArray.includes(layout) ...

Exploring the caching capabilities of NextJS and Vercel for optimizing simple fetch

I have successfully deployed a NextJS (13.2.4) app to Vercel after testing it locally with great results. The issue I am facing is related to a simple fetch request from a component ('use client'). This request is directed towards a route within ...

Unable to execute an Angular 2 application within Visual Studio 2015

I encountered an error while trying to set up an environment on VS 2015 with Angular2. Whenever I run the command "npm start," I receive the following error message. I attempted using "npm cache clean --force" before running "npm start," but the error pers ...

Moving the starting directory of a NodeJS application on Azure

My NodeJS app on Azure was initially written in Javascript with the app.js file located in the root directory. This file was automatically detected during deployment via Git. Recently, I converted the app to Typescript and now have a build directory, with ...

My draggable item seems stuck in place. Any ideas on how to get it moving again?

I have been trying to implement some code I found on this link. Despite adding all the necessary file links, the code is not functioning as expected. It should be able to move within the bounds of a container, but it's not working properly. var max ...

Guide to extracting information from a text file, modifying the content, and then adding it to an HTML document

I have some content stored in a text file which includes HTML with template literals like the following: <html> <head></head> <body> <p>`${abc}`</p> </body> </html> The values are coming from server abc.. M ...

Tips on specifying a default value when receiving data from an API

I am working with a dropdown list that is populated from an API call. Here is my code snippet: <label>User Code:</label> <select ng-options="c as c.User for c in userList" ng-model="selectedUser" id="search3"> </select> To fet ...

Stop allowing users to place periods before their nicknames on Discord servers (Programming in discord.js with a Discord Bot)

I have been working on a script to identify when a user alters their name on Discord by adding a period at the beginning, such as changing "bob" to ".bob". The goal is to prevent this change and keep it as "bob". if (user.nickname.startsWith(".")) { ...

Ways to monitor and measure clicks effectively

Within my website, I have a table element with one column and numerous rows. Each row serves as a hyperlink to an external shared drive. <tr><td ><a href="file://xxx">Staff1</a></td></tr> <tr ><td ><a h ...

Connect external script actions to HTML elements within components

I'm attempting to incorporate an external script Within public/index.html <script src="https://embed.selly.gg"></script> An event should trigger when I click on a button with specific data attributes. Inside components/shop/ShopItem.js ...

Issues with utilizing Jquery datepicker within a Vue.js component's v-for loop in Laravel

I am facing an issue with the Jquery date picker inside a v-for loop in my vue.js component. The date picker works fine outside of the loop, but inside the loop it does not behave as expected. Here is a snippet of code where the date picker is working cor ...

Struggling with implementing basic i18n and dynamic routing functionality in Next.js

Despite reading the Next.js documentation, completing the tutorial, and reviewing numerous examples, I am still struggling to accomplish a straightforward task with Next.js. In my application, I have two locales: en and de. The route structure is as foll ...

Is it possible to utilize TypeScript code to dynamically update the JSON filter with variable values?

I am dealing with a JSON filter in which the value for firmwareversion needs to be replaced with a dynamic value. Here's how I've set it up: //JSON filter this.comX200FilterValue = '{ "deviceType": "ComX", "firmwareV ...