Introduction
We will be working with Data Structures extensively in this section. We will use JavaScript Arrays a lot. We will discover why a JavaScript Array is not really an Array in the truest sense of the word, but more like a List. You will also learn how to create your own Data Structures in JavaScript. Soon you will be creating and sorting your own Lists in JavaScript.
Let’s do a few warm-up exercises
Write code and unit tests for the functions below.
Swap first two
Create a function:
- That takes a list as a parameter.
- Swap the first and the second entry in the list.
- And returns the resulting list.
Given a list :
['apple', 'pear', 'mango', 'banana'];
It should return :
['pear', 'apple', 'mango', 'banana'];
Swap first and last
Create a function:
- That takes a list as a parameter.
- And swap the first and the last entry in the list.
- And returns the resulting list.
Given a list :
['apple', 'pear', 'mango', 'banana']
It should return :
['banana', 'pear', 'mango', 'apple']
Know they neighbour
Create a function that:
- takes a list of numbers;
- loops through the numbers;
- compares each number with its neighbour to the right;
- if a number is bigger than its neighbour on the right, it should swap with its neighbour.
- returns the resulting list.
What is the result of this function? Where does the biggest number ends up?
Use this data :
[5, 19, 7, 17, 6, 1, 3]
Insights
- What did you learn from writing these functions?
- What was hard?
- What did you struggle with?
- What was useful?