My Codewars Solutions

Welcome to my collection of coding challenges!

Coding Image

Featured Challenges

Explore my solutions to various coding challenges from Codewars.

Challenge 1: Valid Braces

The validBraces function checks if a string of braces (), [], and {} is valid by using a stack. It ensures every opening brace has a corresponding closing brace in the correct order, returning true if valid and false if not.

Challenge 2: Using forEach to Double Array Elements with Index and Array Reference

This JavaScript code demonstrates how to use the forEach method to iterate over an array of numbers. In the first snippet, it simply doubles each number and logs the result to the console. The second snippet enhances the functionality by not only doubling each number but also logging the element's index and the entire array during each iteration.

Challenge 3: Reversing Signs and Sorting an Array of Numbers

This JavaScript code takes an array of numbers, changes the sign of each element (negatives become positives and positives become negatives), and then sorts the resu lting array in ascending order. The final sorted array is logged to the console.

Challenge 4 : Counting Letter Frequencies in an Array

This code counts the occurrences of each letter in an array using an object. It iterates through the array with forEach, updating the count for each letter and logs the result.

Challenge 5 : Counting Specific Values in an Array

This code snippet defines a function that counts how many times a specified value appears within an array of numbers. Given an array of scores, it demonstrates how to find the frequency of occurrences of the number 100 in that array using the reduce method. The result is then printed to the console.

Challenge 6 : Exploring Primitive Data Types in JavaScript

This code snippet demonstrates how to check the primitive data types in JavaScript using the typeof operator. It shows that numerical values (like 2.5) are of type number, strings (like "one two three") are classified as string, and boolean values (such as false) are identified as boolean.

Challenge 7 : Understanding Objects as Associative Arrays in JS

This section introduces objects in JavaScript as associative arrays, where properties are accessed by unique keys instead of numerical indexes. The provided example defines an object, sampleObject, with several properties and demonstrates updating and accessing these properties, highlighting the flexibility and structure of JavaScript objects.

Challenge 8 : Methods: Functions as Properties in JavaScript Objects

This section describes methods as functions that serve as properties of JavaScript objects, defining their behavior. An example of a point object with properties x and y, along with methods to move the point, demonstrates how methods can change an object's state. The this keyword indicates the object's context within the methods, highlighting the relationship between methods and object properties.

Challenge 9 : Deleting Object Properties in JavaScript

This code snippet demonstrates how to delete the work property from the email object within a contact object. After the deletion, it logs the result of accessing work (which outputs undefined) and verifies that the private email property still exists and outputs its value, "victoireushindi371@gmail.com.

Challenge 10 : Modifying Object Properties in JavaScript

This code shows how to update a property in a JavaScript object. It highlights the error that occurs when trying to access a property with a space in its name using incorrect syntax.

Challenge 11 : Iterating Over Object Properties in JavaScript

This code snippet demonstrates how to loop through specific properties of a JavaScript object (contact) by dynamically constructing the property names ("email_1" and "email_2") within a for loop and logging their values to the console.

Challenge 12 : Clothing Selector Based on Temperature

The getClothing function provides clothing recommendations based on the isCold boolean input, returning "Grab a jacket!" for cold weather and "It’s a shorts kind of day." for warm weather. It utilizes block-scoping with let for the messages.

Challenge 13 : Default Notes for Contact Object

This code creates a contact object and checks if the notes property is undefined. If it is, it sets notes to "something really important" and logs this value.

Challenge 14 : Circle Area Calculator

This JavaScript code calculates and logs the area of a circle with a radius of 5 using the formula Area = π×r×r. The calculation is performed when the webpage finishes loading. The area is logged as 78.55 in the console.

Challenge 15 : Circle Area Calculation with Scope Example

This JavaScript code calculates the area of a circle using local and global variables. On page load, it logs the global pi (3.142) and calculates the area using a local pi (10). The area of the circle with radius 5 is logged as 250.

Challenge 16 : Displaying Meat Options in the Console

This JavaScript code waits for the window to load, then defines an array of meat types. After the window loads, it logs each meat type to the console, separated by spaces, using the spread operator for easy visibility in debugging or informational contexts.

Challenge 17 : Merging Arrays Using the Spread Operator

This code merges an array of numbers (1-5) with additional numbers (6-10) using the spread operator and logs the result to the console.

Challenge 18 : Basic String Interpolation

This code defines an array with three numbers (3, 5, 7) and a function that adds its three arguments. It uses the spread operator to pass the array elements as individual arguments to the function and logs the sum (15) to the console.

Challenge 19 : Adding Numbers with the Spread Operator

This example demonstrates how to use template strings for simple variable interpolation. The value of the name variable is inserted into the greeting string, resulting in "Hello, Victoire!

Challenge 20 : Multi-line Strings

 This example shows how template strings can create multi-line strings without the need for concatenation or escape characters. The output maintains the line breaks as shown in the code.

Challenge 21 : Expressions inside Template Strings

Here, template strings can embed expressions directly within the string. The values of a and b, as well as their sum, are calculated and included seamlessly in the output: "The sum of 5 and 10 is 15."

Challenge 22 : Function Call inside Template String

In this example, a method within an object uses a template string to create a greeting. The properties name and age are interpolated, producing "My name is Bob and I am 30 years old."

Challenge 23 : Multi-line Template String Example

This code snippet runs when the window loads, creating a multi-line string using template literals. The string greets and introduces "Victor," maintaining the format with line breaks. Inspect the page to check the output in tthe console

Challenge 24 : Checking for Substring Presence

 In this example, includes() is used to check if the substring "fox" exists within the sentence. It returns true, indicating that the substring is present.

Challenge 25 : Verifying String Start

This example demonstrates startsWith(), which checks if the string greeting starts with "Hello". The method returns true, confirming the string begins with the specified value.

Challenge 26 : Confirming String End

Here, endsWith() is used to verify if the filename ends with ".pdf". The method returns true, indicating that the string concludes with the specified suffix.

Challenge 27 : Repeating a String

In this example, repeat() is employed to create a string by repeating "ha" three times, resulting in "hahahaha!!!". This method is useful for generating repeated patterns efficiently.

Challenge 28 : Replacing Substring in a String

This code replaces "World" with "Codewars" in the string "Hello World!!" and logs "Hello Codewars!!" to the console upon window load. It illustrates the use of the replace() method in JavaScript.

Challenge 29 : Checking String Start with Offset

This code checks if "goodbye" starts with "by" from the 4th index, returning true. The result is logged to the console upon window load.

Challenge 30: Checking String End with Offset

 This code checks if "goodbye" ends with "good" when assessing up to the 3rd last character, returning true. The result is logged to the console on window load.

Challenge 31 : Ninja Chop Simulation

This code defines a ninja object with a method called chop, which simulates a chopping action by logging a message to the console every second. The method takes a parameter x, which represents the number of times the ninja will "chop" before stopping. The window.onload function ensures that the simulation starts once the webpage has fully loaded.

Challenge 32:  Simple Addition with Arrow Function

This code defines an arrow function add that takes two parameters, a and b, and returns their sum. When called with arguments 2 and 3, it logs 5 to the console.

Challenge 33: Greeting with No Parameters

This code defines an arrow function greet that takes no parameters and returns the string "Hello, World!". It logs the greeting to the console when called.

Challenge 34: Squaring a Number

This code illustrates an arrow function square that takes a single parameter x and returns its square. When called with 4, it logs 16 to the console.

Challenge 35: Multiplying and Logging

Here, the arrow function multiplyAndLog accepts two parameters, multiplies them, logs the result, and returns it. When called with 3 and 5, it logs 15 to the console.

Challenge 36: Ninja Chop Simulation

This code defines a ninja object with a method called chop, which simulates a chopping action by logging a message to the console every second. The method takes a parameter x, which represents the number of times the ninja will "chop" before stopping. The window.onload function ensures that the simulation starts once the webpage has fully loaded.

Challenge 37: Basic Set Creation

This code creates a new Set called mySet initialized with the numbers 1 to 5. It logs the Set, which contains these unique values.

Challenge 38: Adding Unique Values to a Set

In this example, a new Set is created, and the values 1 and 2 are added. Adding 1 again (a duplicate) has no effect. The logged Set contains only the unique values 1 and 2.

Challenge 39: Checking for Existence of a Value

This code creates a Set with the letters 'a', 'b', and 'c'. The has method checks for the presence of 'b' (returns true) and 'd' (returns false), which are logged to the console.

Challenge 40: Removing a Value from a Set

This code initializes a Set with the values 1, 2, and 3. The delete method removes the value 2, and the logged Set now contains only 1 and 3.

Challenge 41: Iterating Over a Set

This example demonstrates the use of the forEach method to iterate over a Set. Each value in the Set (1, 2, 3) is logged to the console in turn.

Challenge 42: Set Operations with Name Management

This code snippet illustrates the use of a JavaScript Set to manage a collection of unique names. It initializes a Set, adds several names (including a duplicate), and removes one name. The code checks for the presence of a specific name (Victoire), attempts to delete a name that has already been removed, and logs the size of the Set along with its current contents. The Set ensures that only unique names are stored, demonstrating its capabilities in handling duplicates and membership checks.

Challenge 43: Removing Duplicates from Family Members List

This code snippet demonstrates how to remove duplicate names from an array of family members using a JavaScript Set. It starts with an array that contains several names, including duplicates. By creating a Set from the array, it automatically filters out the duplicates. The code then converts the Set back into an array and logs both the unique Set and the refined array of family members to the console. This showcases the effectiveness of Set in managing unique values in JavaScript.

Challenge 44: Use of let

This is the correct way to use let. Use let to declare variables when you plan on changing the value of a variable later in your code.

Challenge 45: Refactoring Variable Declarations to Use Let and Const

This code refactor demonstrates the conversion of variable declarations from var to let and const in a JavaScript program. By using const for unchanging constants and arrays, and let for block-scoped variables such as loop indices, the code enhances readability, maintains better scoping practices, and prevents potential issues related to variable hoisting and reassignment.

Challenge 46: Student Report Card Notification

This code defines objects for a student and a teacher, constructs a message instructing the student to meet the teacher in a specified room to pick up their report card. Prior to ES6, the old way to concatenate strings together was by using the string concatenation operator ( + ).

Challenge 47: Create Animal Trading Card HTML

This code constructs a multi-line note to the teacher, excusing the student for being ill. It demonstrates the use of string concatenation with the newline character (\n) to format the note across multiple lines, which can become complex compared to single-line strings.

Challenge 48: Multi-line Message for Teacher

This code defines an object for a cheetah and a function that generates an HTML trading card for the animal using template literals, allowing for cleaner and more readable multi-line strings. It replaces the concatenation with ${} syntax to interpolate the object properties directly into the HTML structure.

Challenge 49: Functions

Create reusable functions to encapsulate logic.

Challenge 50: Event Handling

Learn to handle events in the DOM using JavaScript.

Challenge 51: Simple Promise Example

This code creates a Promise that resolves if a simple condition (1 + 1 equals 2) is met, otherwise it rejects. A promise that resolves with the string 'success' or rejects with the string 'failed'.

Challenge 52: Simulated Asynchronous Operation

his code creates a promise that simulates an asynchronous operation with a delay of 1 second. The promise resolves with "OK" if the operation is successful, otherwise it rejects with "Error".

Challenge 53: JavaScript Message Display

This code defines a function to display messages in the console. It calls this function with "Hello" and "Goodbye" to demonstrate simple function usage.

Challenge 54: Function Sequence

JavaScript functions are executed in the sequence they are called. Goodbye

Challenge 55: Function Sequence 2

JavaScript functions are executed in the sequence they are called. The result of the calculation is: 15

Challenge 56: Default Parameter Values in a Function

This code provides a greet function that uses parameter checks to set default values for name and greeting. If no arguments are passed, it defaults to greeting "Student" with "Welcome".

Challenge 57: Defaults and destructuring objects

Just like array destructuring with array defaults, a function can have an object be a default parameter and use object destructuring:

Challenge 58: Defaults and destructuring arrays

You can combine default function parameters with destructuring(opens i n a new tab) to create some pretty powerful functions!

Challenge 59: Inheritance in JS Classes

This JavaScript code demonstrates class inheritance with a base Animal class and derived classes (Rabbit, Fish, Hawk) that share common properties and behaviors, utilizing the super keyword to access parent class methods and properties.

Challenge 60: Tree and Maple Class Implementation

This code defines a Tree class and a Maple subclass that manage tree attributes and seasonal changes. The Tree class initializes properties like size and leaf colors based on seasons, while the Maple class adds functionality to manage sap quantity and gather syrup, as well as overrides methods to adjust syrup during seasonal changes.

Challenge 61: Callback Functions

This code snipped is all about JavaScript Function and Callback Function

Challenge 62: Building Classes and Subclasses

Create a Bicycle subclass that extends the Vehicle class. The Bicycle subclass should override Vehicle's constructor function by changing the default values for wheels from 4 to 2 and horn from 'beep beep' to 'honk honk'.

Challenge 63: ES6 Symbols

A symbol is a unique and immutable data type that is often used to identify object properties. To create a symbol, you write Symbol() with an optional string as its description. const sym1 = Symbol('apple'); console.log(sym1); Symbol(apple)

Challenge 64: ES6 The Iterable Protocol

The iterable protocol is used for defining and customizing the iteration behavior of objects.

Challenge 65: ES6 The Iterator Protocol

The iterator protocol is used to define a standard way that an object produces a sequence of values. What that really means is you now have a process for defining how an object will iterate. This is done through implementing the .next() method.

Challenge 66: Checking The Length of a Set

This code snippet demonstrates how to check the length of a Set in JavaScript. It creates a Set with # unique values and logs the size of the Set to the console. The output shows that the Set contains # elements.

Challenge 67: Using the SetIterator

Because the .values() method returns a new iterator object (called SetIterator), you can store that iterator object in a variable and loop through each item in the Set using .next().

Challenge 68: Using a for...of Loop

An easier method to loop through the items in a Set is the for...of loop.

Challenge 69: Managing Favorite Ice Cream Flavors Loop

This code creates a Set to store unique ice cream flavors, adds four flavors, removes "strawberry," and logs the remaining flavors.

Challenge 70: WeakSets

A WeakSet is just like a normal Set with a few key differences:

  1. a WeakSet can only contain objects
  2. a WeakSet is not iterable which means it can’t be looped over
  3. a WeakSet does not have a .clear() method

Challenge 71: Managing Flavor Objects with WeakSet

This snippet shows how to create a WeakSet in JavaScript to store unique flavor objects. It defines two flavor objects and adds them to the WeakSet, ensuring only unique references are kept.

Challenge 72: Sort Object by Values in Descending Order

This function converts an object into an array, sorts it by values from highest to lowest, and then maps it back to strings formatted as "key: value".

Challenge 73: Math.random();

The purpose of Math.random() is to generate a random decimal number between 0 (inclusive) and 1 (exclusive). It's useful in situations where you need unpredictability, like: Creating random game elements (e.g., random positions, dice rolls) Randomizing choices or options Simulating chance or probability events Generating random values for experiments or simulations In short, it helps introduce randomness into your programs!

Challenge 73: Exercise 1

Generate a random number and display it in the console.

Challenge 74: Exercise 2

Generate five random numbers and store them in an array.

Challenge 75: Exercise 3

Create a function that returns a random number between 0 and 1 when called.

Challenge 76: Exercise 4

Generate a random number and check if it’s greater than 0.5. Log "High" if yes, otherwise "Low".

Challenge 77: Exercise 5

Generate a random number, multiply it by 10, and round it to the nearest whole number.

Challenge 78: Floor Method

Math.floor() is a JavaScript method that rounds a decimal down to the nearest whole number (integer).

Challenge 79: Remainder / Modulo Operator

The code calculates and prints the number of full weeks and remaining days in a year (assuming 365 days).

Challenge 80: Food Choice with Switch Statement

This code uses a switch statement to check the value of the food variable (which is set to 'salad'). Since 'salad' doesn't match the case values 'oyster' or 'pizza', the default case is executed, printing "Enjoy your meal" to the console

Challenge 81: Deleting Object Properties in JavaScript

The code demonstrates how to delete a property from a nested object in JavaScript. It initializes a contact object with email addresses, then uses the delete operator to remove the work email property. Consequently, accessing the deleted property returns undefined, while accessing other existing properties returns their values.

Challenge 82: Adding a New Email Address to a Contact

The code initializes a contact with known email addresses, adds a new "other" email address, and then logs all existing email addresses to verify the additions.

Challenge 83: Understanding JavaScript Object Property Assignment

This JavaScript code snippet demonstrates the correct way to access and modify properties within an object. The code shows that while you can use bracket notation (e.g., contact["first name"]) to access properties, especially those with spaces in their names, attempting to use dot notation (e.g., contact.first name) with a space or string directly causes a syntax error. This highlights the importance of using bracket notation when property names contain spaces or are dynamically determined.

Challenge 84: Default Notes Initialization

This code initializes a contact object with a name and email. It then checks if the notes property exists. If notes is falsy (e.g., undefined), it sets contact.notes to "something really important". Finally, it prints the updated contact object to the console.

Challenge 85: Accessing a Property with Existence Check

This code snippet demonstrates how to access a property ('notes') of an object ('contact') and print its value to the console after first verifying that the property exists within the object using the in operator. This prevents errors that might occur if the property was undefined.

Challenge 86: Iterating Through a Contact Object

This code snippet defines a contact object with telephone and email properties. It then uses a for...in loop to iterate through the object's properties, printing each property name to the console.

Challenge 87: Calculate average

Write a function which calculates the average of the numbers in a given array.

Challenge 88: Thinkful - Logic Drills: Traffic light

You're writing code to control your town's traffic lights. You need a function to handle each change from green, to yellow, to red, and then to green again. Complete the function that takes a string as an argument representing the current state of the light and returns a string representing the state the light should change to. For example, when the input is green, output should be yellow.

Challenge 89: Array Sum with reduce()

Adds all numbers in an array, resulting in 15.

Challenge 90: Welcome to the City

Create a method that takes as input a name, city, and state to welcome a person. Note that name will be an array consisting of one or more values that should be joined together with one space between each, and the length of the name array in test cases will vary.

Challenge 91: Count of positives / sum of negatives

Given an array of integers. Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. 0 is neither positive nor negative. If the input is an empty array or is null, return an empty array.

Challenge 92: Sort and Star

You will be given a list of strings. You must sort it alphabetically (case-sensitive, and based on the ASCII values of the chars) and then return the first value. The returned value must be a string, and have "***" between each of its letters.

Challenge 93: Understanding Object.assign() in JavaScript: Copying Properties and Object Independence

This code demonstrates how Object.assign() copies properties from one object to another, creating a new object with the same property values but different references. It highlights that while objects may have identical content, they are considered different in memory unless they share the same reference.

Challenge 94: Using Object.assign() to Update and Extend an Object in JavaScript

This snippet shows how Object.assign() updates an existing object by adding new properties and overwriting existing ones. Here, it adds age and updates country in the me object, resulting in a combined object with the latest property values.

Challenge 95: Array.prototype.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. It does not execute the function for empty elements. In this example, it is used to create a new array of squares from an existing array of numbers.

Challenge 96: Simple Regular Expression Pattern Matching Example

Demonstrates the use of a regular expression in JavaScript to test whether the string "hello" appears at the beginning of a given input string. The code logs the result of testing two different strings against the pattern.

Challenge 97: Regular Expression: Digit Matcher

This regular expression pattern matches any single digit character (0-9). Useful for validating or extracting numeric digits from strings.

Challenge 98: Regular Expression: Exact Match for "cat"

This regular expression pattern matches only the exact string "cat". It does not match substrings or variations; the input must be exactly "cat".

Challenge 99: Regular expression to match words that start with the letter 'b'.

This pattern uses the word boundary anchor (`\b`) to ensure that the match occurs at the start of a word, followed by the letter 'b' and then zero or more word characters (`\w*`). The global flag (`g`) allows matching all occurrences in a string.

Challenge 100: hello - Greets and executes a callback

This function logs "Hello!" to the console and then invokes the provided callback function.

Challenge 101: Callback Function Example: Summing Two Numbers

This code defines a sum function that adds two numbers and passes the result to a callback function. It demonstrates using callbacks by printing the sum to the console with a separate displayConsole function.

Challenge 102: Checks if elements in an array represent vowel character codes and replaces them with the corresponding vowel character.

@param {number[]} a - An array of numbers representing character codes. @returns {(number|string)[]} A new array where numbers corresponding to vowels are replaced by their character, others remain unchanged.

Challenge 103: Convert Character Codes to Letters Using `map` in JavaScript

This code converts an array of character codes to their corresponding letters using `String.fromCharCode` and logs each letter to the console.

Challenge 104: Check for Vowels Using Regular Expressions in JavaScript

This code uses a regular expression (/[aeiou]/) with the .test() method to check if a string contains at least one lowercase vowel (a, e, i, o, or u). It logs true if a vowel is found and false otherwise.

Challenge 105: Using Array.from() for String and Array Transformation in JavaScript

This code demonstrates how Array.from() can convert a string into an array of characters and how it can transform each element of an array using a mapping function. The first line outputs an array of characters from the string "food", while the second line outputs a new array where each number from [1,2,3] is doubled.

Challenge 106: Using Array.from() for String and Array Transformation in JavaScript

This function iterates through each character of a given string, checks if it is a vowel (a, e, i, o, u), and returns the total number of vowels found.

Challenge 107: Get Character and Character Code at Index in a String

This code retrieves the character and its Unicode code point from a specific index in a string, then logs both values to the console.

Challenge 108: Convert String to Array of Character Codes in JavaScript

This code defines a function that takes a string and returns an array containing the Unicode character codes for each character in the string. It demonstrates the conversion using the example name "Victoire".

Challenge 109: Extract Vowels from a String in JavaScript

This code defines a function extractVowels that takes a string and returns a new string containing only the vowels from the original input, preserving their order and case.

Challenge 110: Repeat a String N Times with Input Validation

This code defines a function repeatString(n, s) that returns a string s repeated n times. If n is not a positive integer, it returns an error message. The function uses a for loop to concatenate the string s n times.