1, Create a countdown using recursion

Title Description:

A function countdown has been defined, which has a parameter (n). The function should be called recursively based on parameter n, returning an array of consecutive numbers from n to 1. If the function is called with a parameter less than 1, the function should return an empty array.

Test requirements:

Enter a parameter n and finally return the array [n,n-1,n-2,..., 2,1]. If countdown(5) is called, output [5, 4, 3, 2, 1]

Solution:

```function countdown(n){
if(n<1) {
return [];
} else {
var arr=countdown(n-1);
arr.unshift(n);
return arr;
}
}
```

2, Create a sequence of numbers using recursion

Title Description:

The rangeOfNumbers function has been defined and contains two parameters. The function should return an array of consecutive numbers, starting with the startNum parameter and ending with the endNum parameter. The starting number is less than or equal to the ending number. A function must call itself recursively and cannot use any form of loop. Consider that startNum and endNum are the same.

Test requirements:

To output the integer of the interval [startNum,endNum] in the array, if rangeOfNumbers(1, 4), output the array [1,2,3,4]
If rangeOfNumbers(5, 5) is equal, the array [5] is output

Solution:

```function rangeOfNumbers(startNum, endNum) {
if(startNum==endNum){
return [startNum]
}else {
var arr=rangeOfNumbers(startNum,endNum-1);
arr.push(endNum);
return arr
}
}
```

3, Record set

Title Description:

Given an object, it is used to represent some music album collections. Each album has several attributes and a unique id number as key values. Not all albums have complete information.
Start with the updateRecords function, which requires an object records, including a music album collection, an id, a prop (such as artist or tracks), and a value. Use the following rules to complete the function to modify the object passed to the function.

Rule Description:

• The function must always return the entire music album collection object.
• If prop is not tracks and value is not an empty string, update - or set the prop of the album to value.
• If prop is tracks but the album has no tracks attribute, create an empty array and add value to it.
• If prop is tracks and value is not an empty string, add value to the end of the album's existing tracks array.
• If value is an empty string, delete the specified prop from the album.

Test requirements:

test caseresult
updateRecords(recordCollection, 5439, "artist", "ABBA")The value of artist should be the string ABBA
updateRecords(recordCollection, 5439, "tracks", "Take a Chance on Me")The last element of tracks should be the string Take a Chance on Me
updateRecords(recordCollection, 2548, "artist", "")artist should not be set to any value
updateRecords(recordCollection, 1245, "tracks", "Addicted to Love")The last element of tracks should be the string added to love
updateRecords(recordCollection, 2468, "tracks", "Free")The first element of tracks should be a string
updateRecords(recordCollection, 2548, "tracks", "")tracks should not be set to any value
updateRecords(recordCollection, 1245, "albumTitle", "Riptide")The value of albumTitle should be the string Riptide

Solution:

```var recordCollection = {
2548: {
albumTitle: 'Slippery When Wet',
artist: 'Bon Jovi',
tracks: ['Let It Rock', 'You Give Love a Bad Name']
},
2468: {
albumTitle: '1999',
artist: 'Prince',
tracks: ['1999', 'Little Red Corvette']
},
1245: {
artist: 'Robert Palmer',
tracks: []
},
5439: {
albumTitle: 'ABBA Gold'
}
}
function updateRecords(records, id, prop, value) {
if(value=='') {
delete records[id][prop]
} else if (prop!="tracks"){
records[id][prop]=value
} else if (prop=='tracks') {
if(!records[id].hasOwnProperty('tracks')) {
records[id][prop] = []
}
records[id][prop].push(value)
}
return records
}

updateRecords(recordCollection, 5439, 'artist', 'ABBA')

```

Note: first judge whether value is null, otherwise judge whether it is null at every step

4, Blackjack game

Algorithm description:

In the casino blackjack game, players can maintain their advantage in the game by calculating the high and low values of the cards issued on the card table. This is called the 21 point algorithm.

Title Description:

Write a function to realize the 21 point algorithm. It increments or decrements the global variable count according to the value of the parameter card (see the table, which may be a number or string). Then the function returns a string spliced by the current count and Bet (when count > 0) or Hold (when count < = 0). Note that there should be a space between the count and the player's decision (Bet or Hold).

Rule Description:

There are more high-value cards on the card table, which is beneficial to players. According to the table below, each card is assigned a value. If the value of the card is greater than 0, the player should increase the bet. If the value of the card is 0 or negative, the player should add a few bets or even no bets.

countCards
+12, 3, 4, 5, 6
07,8,9
-110, 'J', 'Q', 'K', 'A'

Test requirements:

The result of calling cc(n) is: - 3 Hold or 5 Bet

Solution:

```let count = 0;

function cc(card) {
switch (card) {
case 2:
case 3:
case 4:
case 5:
case 6:
count++
break
case 10:
case "J":
case "Q":
case "K":
case "A":
count--
break
}
if (count <= 0) {
return count + " Hold"
}
return count + " Bet"
}

cc(2); cc(3); cc(7); cc('K'); cc('A');
```

Note: when the value of card is 7,8,9, it does not increase or decrease, which can be ignored at this time. Bet means to continue to add bets, Hold means not to add bets, and judge whether to add bets according to the calculated value.

5, Golf code

Title Description:

In the golf game, each hole has its own par, which represents the average number of strokes that the ball swings into the hole. There is a different nickname (representing the level of playing golf) according to how many strokes you swing into the hole are higher or lower than par.

Rule Description:

The function will pass two parameters, par and strokes. Return the correct string according to the following table. The following table lists the strings corresponding to different swings (from high to low).

Swing timesReturn string
1"Hole-in-one!"
<=par -2"Eagle"
par - 1"Birdie"
par"Par"
par+1"Bogey"
par+2"Double Bogey"
>= par + 3"Go Home!"

Test requirements:

testresult
golfScore(4, 1)Hole-in-one!
golfScore(4, 2)Eagle
golfScore(5, 2)Eagle
golfScore(4, 3)Birdie
golfScore(4, 4)Par
golfScore(1, 1)Hole-in-one!
golfScore(5, 5)Par
golfScore(4, 5)Bogey
golfScore(4, 6)Double Bogey
golfScore(4, 7)Go Home!

Solution:

```const names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];

function golfScore(par, strokes) {
if (strokes == 1)
return "Hole-in-one!";
else if (strokes <= par - 2)
return "Eagle";
else if (strokes == par - 1)
return "Birdie";
else if (strokes == par)
return "Par";
else if (strokes == par + 1)
return "Bogey";
else if (strokes == par + 2)
return "Double Bogey";
else if (strokes >= par + 3)
return "Go Home!";
}

golfScore(5, 4);
```

Note: par and strokes must be numbers and positive.

6, Data search

Title Description:

We have an object array that stores the address book. The lookUpProfile function has written parameters, and the name and attribute (prop) parameters are required. The function will check whether there is a contact with the same firstName as the incoming name in the address book.

Test requirements:

• If name exists, you also need to check whether the prop attribute exists in the corresponding contact
• If both exist, the function returns the value corresponding to the prop attribute.
• If name does not correspond to any contact, then return the string No such contact.
• If the prop property does not exist in the contact matching the name, No such property is returned.

Solution:

```// set up
const contacts = [
{
firstName: "Akira",
lastName: "Laine",
number: "0543236543",
likes: ["Pizza", "Coding", "Brownie Points"],
},
{
firstName: "Harry",
lastName: "Potter",
number: "0994372684",
likes: ["Hogwarts", "Magic", "Hagrid"],
},
{
firstName: "Sherlock",
lastName: "Holmes",
number: "0487345643",
likes: ["Intriguing Cases", "Violin"],
},
{
firstName: "Kristian",
lastName: "Vos",
number: "unknown",
likes: ["JavaScript", "Gaming", "Foxes"],
},
];

function lookUpProfile(name, prop) {
for (var i = 0; i < contacts.length; i++) {
if (name == contacts[i]["firstName"]) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
}

lookUpProfile("Akira", "likes");
```

Why not use the following code snippet?

The function of this code segment is to judge whether the first object meets the requirements and does not meet the requirements of the topic

```    function lookUpProfile(name, prop) {
for (var i = 0; i < contacts.length; i++) {
if (name == contacts[i]["firstName"]) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
} else {
return "No such contact";
}
}
}
```

be careful:

1. . hasOwnProperty() directly refers to the property name in parentheses without quotation marks

2. After your code runs, does the name attribute value always display "No such contact" except entering name=Akira?

The reason is that you return "No such contact"; This statement is put into the for loop! At this time, only the first element of the object array is traversed, that is, the function is only used to judge whether the first object meets the requirements... This is not what we want, what we want is that it can traverse all objects... So we should wait until it is traversed (that is, put the statement return "No such contact" outside the for loop). If it is not satisfied, return "No such contact"

1. Does your code always show undefined after running?

Check whether your return statement reads like this: return contacts [i] prop; Because prop is a formal parameter, the corresponding argument title gives the string type, and the point (.) The operator cannot be followed by a string, so the correct writing method is: return contacts[i][prop]

See this, if you think it's OK, just praise it!!! If you have other different ideas, please comment

Tags: Javascript

Posted by pagegen on Mon, 18 Apr 2022 02:40:01 +0930