20
Solving Coding Challenges with JavaScript Functions on Autocode
We've been zooming through every day and week, and while it's been challenging to intake so much information in such a short period of time, I'm loving the program's curriculum and structured daily agenda. Our 12 weeks are broken down into 4 units that cover fundamental technologies for full-stack application building.
In this tutorial, we will apply some of the tips that I've learned through General Assembly to strengthen our JavaScript skills and to approach solving coding challenges.
Let's get started! π§π½βπ»π©π½βπ» ππΌ
JavaScript is an essential programming language. These days, you can do everything with it: from selecting and manipulating elements on a website to setting up Node.js servers that can handle millions of requests per second. But before we can begin leveraging the power of JavaScript, we need to master functions.
Functions are fundamental building blocks of JavaScript. They are reusable blocks of code that we can leverage throughout our applications as many times as we need to create our desired functionality. Today we will practice solving 3 challenge JavaScript problems with functions. We will follow four steps to solve each problem:
I've chosen to code on Autocode to help us better understand the power of functions. Autocode is an online code editor and hosting platform that will allow us to easily publish our functions and make them accessible via the web without worrying about setting up hosting through third-party services. Autocode will automatically turn our JavaScript functions into HTTP(S) endpoints. π€―
Let's get started! π©π½βπ»
Head on over to Autocode.com and sign up for a free account. Choose a subdomain where your projects will be hosted and set a password.
Once you've signed up, navigate to your Project Management dashboard and click New Project.
We will be creating endpoints for each of the 3 functions that we will be coding. An endpoint is a means for you and other external apps to communicate with your system to perform certain actions by making HTTP requests to the URL representing it.
You'll be brought into Autocode's IDE; this is where we will write the logic to solve 3 challenge problems.
From here, there are a few pieces to point out;
- The Event selector is at the top. Here you can choose what type of event will execute the code in your endpoint. For this tutorial, we will use the default, which is a normal HTTP request.
- When you press the green "Run" button, you will be prompted to name your project. Name it
functions
for the tutorial and hit Save new project.
- You'll notice the endpoint URL show up at the bottom of the file. This is where your endpoints will live on the web.
- The Endpoint viewer window shows up in the bottom right. This will show you the results of your endpoint execution. You can use it to view logs as well.
- All Autocode endpoints are immediately available on the web once they're saved.
Great, now that you have set up your coding environment, we can begin with Challenge Problem #1!
Let's tackle it together! π€πΌπ€πΌ
Step 1: Carefully read the problem to understand it
Write a function that returns the greatest common factor between **num1**
and **num2**.
This means that the function should return the largest number that divides both **num1**
and **num2**.
For example, if we pass in the number 6 and number 10 into our function, our function should return 2. Inputting 4 and 8 should return 4 etc...
(6, 10); // => 2
(4, 8); // => 4
(45, 30); // => 15
Let's prepare our coding environment. Head back to Autocode. Create a new endpoint by right-clicking the functions
folder on the left of the browser and selecting New endpoint file
.
Name your file functions/greatestCommonFactor.js
as I have:
You will notice that your new file is pre-populated with a sample hello world function.
Let's take a moment to analyze and understand how this function is created.
The comment in line 1--6
defines the parameter
types that the function takes and the return
type. In this sample, the function is expecting a name
parameter of type string
and it will return a body
of type object.
line 7
is exporting our function with amodule.exports
method. Let's check it out. Change the name in line 7
to your name as I have in the screenshot.
Press the green run
button to test out this sample function. You will see your code executed in the Endpoint viewer window with "Hello <yourName>
, welcome to Autocode!" message.
You can also click the autogenerated endpoint URL on the bottom left, and a new window will open in the browser to display the message:
You can test passing a name
parameter into your function via the URL and press enter to reload the page as I have: ?name=Student
It's that simple to deploy reusable functions through Autocode! If you would like to dive deeper into Autocode's framework, check out FunctionScript on Github!
Now that we understand how to set up functions on Autocode let's begin solving our first challenge problem!
Step 2: Use pseudocode to craft a plan for solving the problem
First, let's begin planning our execution with pseudocode. Pseudocode is a technique that helps programmers plan out an algorithm in a manner that is easy to understand. Pseudocode does not use any coding syntax, but it fully describes the necessary logic to build our functions. This facilitates implementation because we'll translate each line into code using the JavaScript Syntax...easy, right?
Let's try it!
Reread the problem as many times as needed and begin pseudocoding when ready:
Write a function that returns the greatest common factor between **num1**
and **num2**.
This means that the function should return the largest number that divides both **num1**
and **num2**.
For example, if we pass in the number 6 and number 10 into our function, our function should return 2. Inputting 4 and 8 should return 4 etc...
(6, 10); // => 2
(4, 8); // => 4
(45, 30); // => 15
Pseudocode:
//First we need to define the functions expected parameters and return types in a comment
//Then we use module.exports to export our function and pass in two numbers (num1, num2) as parameters
//We will set a for loop with the iterator (i) set to num1
//As long as i is greater or equal to 1 continue the for loop
//Everytime the for loop continues decrement i by 1
//As we decrement we check to see if num1 modulo i is equal to zero and if num2 modulo i is equal to zero
//If both conditions are met then we will return i
//If the conditions aren't met then we have our for loop continue decrementing until both are both are met
Step 3: Code it out on Autocode!
Now that we've planned out how to solve our challenge problem, we're ready to code it out.
Delete the sample hello world function inside the IDE.
Translate your pseudocode approach to JavaScript syntax inside the IDE as I have:
/**
* My greatestCommonFactor function
* @param {number} num1 First number
* @param {number} num2 Second number
* @returns {number} i
*/
module.exports = async(num1, num2) => {
for (let i = num1; i >= 1; i--) {
if (num1 % i === 0 && num2 % i === 0) {
return i;
}
}
}
Step 3: Test and Deploy your solution on Autocode
Select the Payload button on the bottom right. Set test parameters by creating an object setting num1
and num2
as your keys and give them any two numbers you'd like. I've chosen 1550 and 1000
.
Select the green Run button once you've set your test parameters. The greatest common factor of 1550
and 1000
is in fact 50
! Great Job. βοΈ
You can see your function live by clicking the autogenerated URL on the bottom left via your functions docs. To view the docs, select Advanced Settings in the bottom left cornerand then Generated API Reference.
You can test passing in different numbers in the parameters sections and Run yourfunctionto check the greatest common factor as times as your heart desires.
Breakdown of our Solution to challenge problem #1:
Line 1--6: We set type number
for num1
and num2
and a return type of number
for i
Line 8: We export our async function with module.exports
and pass in our two parameters (num1, num2).
Line 9: We use a for loop
and declare num1
to be our iterator i
, as long as i
is greater or equal to 1
we run our for loop and decrement by 1.
Line 10: Our if
statement checks to see if num1
modulo i
is equal to zero, and if num2
modulo i
equal to zero.
Line 11: If either conditionnum1 % i === 0
or num2 % i === 0
returns false
our loop continues and the following return
statement is ignored. When our if
condition returns true,
that means that both conditions are met, and then we return
the iterator i
. The iterator i
is our greatest common factor between num1
and num2
.
We did it! π Congrats! We solved Problem #1. The rest should be a breeze now that you are familiar with Autocode.
Step 1: Take your time reading the problem
Write a function that takes in a name as a string and returns a string representing their nickname. A nickname is the name up to the second vowel repeated twice. See the examples.
Examples:
(Jacob); // => 'JACO-JACO'
(pikachu); // => 'PIKA-PIKA'
(janeth); // => 'JANE-JANE'
Step 2: Begin strategizing with pseudocode!
//First define the functions expected parameter and return type in a comment above the function
//Use module.exports to export the function and pass in a a name as a string
//Create a variable that defines all vowels inside an array
//Create a variable to keep count of vowels and set it equal to 0
//Use for loop to count through every letter in the string (name)
//Create an intermediate variable to save every character in the string
//Inside the for loop condition use indexOf() method to check and count if character is in the index of vowels
//Use toUpperCase() method to convert string to uppercase
//return a string with characters from index 0 to i (including i)
Step 3: Code it out on Autocode!
Create a new endpoint by right-clicking the functions
folder on the left of the browser and select New endpoint file
.
Name your file functions/nickname.js
and translate your pseudocode to JavaScript Syntax.
/**
* My nickname function
* @param {string} name
* @returns {string} str
*/
module.exports = async(name) => {
let vowels = 'AEIOUaeiou'.split('');
let vowelCount = 0;
for (var i = 0; i < name.length; i += 1) {
let char = name[i];
if (vowels.indexOf(char) > -1) {
vowelCount += 1;
if (vowelCount === 2) {
break;
}
}
}
let str = name.slice(0, i + 1).toUpperCase();
return str + '-' + str;
}
Step 3: Test and Deploy your solution on Autocode
Pass in a test name
parameter and select the green Run
button on Autocode to view the results on the console.
And sure enough, when testing different names result in nicknames! π
(Jacob); // => 'JACO-JACO'
(pikachu); // => 'PIKA-PIKA'
(janeth); // => 'JANE-JANE'
Breakdown of our Solution:
Line 1--5: We set a parameter type string
for name
and a return type of string
Line 7: Weexport our async function with module.exports
and pass in our (name)
parameter
Line 8: We define our vowels and use the split method to break our string of vowels into an array
vowels = [ 'A', 'E', 'I'...,'a', 'e', 'i'...]
Line 9: We set our count equal to zero
Line 10: We use a for loop
to iterate through every character in name
Line 11: We set an intermediate variable to return every character in the string
Line 12: The if condition checks to see if a character is found in the index of vowels: vowels.indexOf(char)
and returns the char location in the vowels array. If the char isn't in the index of vowels, then a -1 is returned, and the loop continues to the next character. If its location is greater than -1, then the logic continues.
Line 13: If the location is greater than -1
we increment our vowelCount
by one.
Line 14: We check to see if the vowelCount
is 2, if false
is returned, we skip the if
statement and move on to the next letter, if true
is returned that means that we have now counted two vowels, and we break out of the for loop.
Line 20: We use the slice()
method to grab the characters starting at index 0
and ending at i
, we add 1
to i
because the slice
method doesn't include the end value. We also use toUpperCase()
method to convert all the letters in our string to uppercase.
Line 21: We return
the string plus a dash plus another string to have our result resemble the examples in the question
Step 1: Read Carefully.
Write a function that takes in an array of strings and returns a new array containing only elements that appeared an even number of times in the input array.
Examples:
const arr1 = ['a', 'b', 'b', 'c', 'd', 'c', 'c', 'd']\
oddOnesOut(arr1); // => [ 'b', 'd' ]
const arr2 = ['fish', 'fish', 'dog', 'cat', 'dog', 'dog']\
oddOnesOut(arr2); // => [ 'fish' ]
Step 1: Pseudo Code
Let's strategize!
//Create a helper function to count our elements in an array
//The helper function has one parameter that takes in an array of strings
//Use a for loop in the helper function to count our elements in the array
//Create and export a second function with a for loop to count the even elements
//Push the even elements into a new array
//Return that new array
Step 2: Code it out on Autocode!
Create a new endpoint by right-clicking the functions
folder on the left of the browser and select New endpoint file
.
Name it functions/oddOnesOut.js.
Delete the sample function and translate your pseudocode to JavaScript syntax as I have:
/**
* My oddOnesOut function
* @param {array} array
* @returns {array} str
*/
function elementCount(array) {
let countObj = {};
for (let i = 0; i < array.length; i += 1) {
let key = array[i];
if (countObj[key] === undefined) {
countObj[key] = 1;
} else {
countObj[key] += 1;
}
}
return countObj;
}
module.exports = async(array) => {
let count = elementCount(array);
const result = [];
for (let key in count) {
let value = count[key]
if (value % 2 === 0) {
result.push(key);
}
}
return result;
}
Step 3: Test and Deploy your solution on Autocode
Pass in a test array
parameter inside the payload window:
{"array": ['fish', 'fish', 'dog', 'cat', 'dog', 'dog']}
Select the green Run
button on Autocode to view the results on the console:
Your function will filter the odd elements out and return the following:
["fish"]
Great job!
Breakdown of Solution:
Line 1--5: We set a parameter type array
for array
and a return type of array
for str
Line 7: We define a helper function elementCount
that takes in an array
of strings
Line 8: Wedeclare a countObj
variable and initialize it to an empty object. This is where we store the different counts of elements in an array.
Line 10: We iterate through the array using a for loop
. We declare 0
to be our iterator (i
), as long as i
is smaller than the length of our array, we run our for loop and increment by 1
.
Line 11: We set key
as an intermediate variable that will give access to the element as we go through the for loop
.
Line 13: We add a condition that checks to see if our countObject
at index key
is undefined. This condition will return true
if the countobject
does not contain the Key
(element) that we're passing in.
Line 14: Whenthe condition returns true
we set countObj[Key]
equal to 1
If the condition is false
which means that our key
is already in the object, then we ignore this statement and move on to the next.
Line 15- 16: If our key
is already stored in the countObj
then we increment our key count by 1.
Line 20: We return the coutObj
Line 23: We export our second function that takes in an array of elements we want to count
Line 24: We declare a variable count
and set it to the object returned from the previous helper function elementCount(array)
Line 25: We define a variable result
and initialize it to an empty array where we will be pushing the elements that show up an even number of times
Line 27: We use a for...in loop to iterate through the count
object and check if the key has a value of modulo 0.
A **for...in* loop is good for looping through all the key-value pairs in an Object.
Line 28: We set a variable value
to count[key]
Line 29: Check to see if the key
has a value
modulo 0
Line 30: If the condition is true, then we push that key
to our result
variable
Line 34: Return the result
That's it for now and thank you for reading! I hope you found this tutorial helpful. I'd love to hear from you if you have any questions. Feel welcome to email me at [email protected]. I'll be happy to help!
20