Skip to content

Commit 1ed1a90

Browse files
authored
Merge pull request #56 from arindal1/main
Added: 3 JavaScript codes
2 parents 71bcea9 + 8bff86e commit 1ed1a90

File tree

6 files changed

+257
-0
lines changed

6 files changed

+257
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const cancellable = (generator) => {
2+
let cancel;
3+
const cancelPromise = new Promise((_, reject) => {
4+
cancel = () => reject("Cancelled");
5+
});
6+
// Every Promise rejection has to be caught.
7+
cancelPromise.catch(() => {});
8+
9+
const promise = (async () => {
10+
let next = generator.next();
11+
while (!next.done) {
12+
try {
13+
next = generator.next(await Promise.race([next.value, cancelPromise]));
14+
} catch (e) {
15+
next = generator.throw(e);
16+
}
17+
}
18+
return next.value;
19+
})();
20+
21+
return [cancel, promise];
22+
};
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# 2650. Design Cancellable Function
2+
[LeetCode](https://leetcode.com/problems/design-cancellable-function/)
3+
4+
Sometimes you have a long running task, and you may wish to cancel it before it completes. To help with this goal, write a function `cancellable` that accepts a generator object and returns an array of two values: a cancel function and a promise.
5+
You may assume the generator function will only yield promises. It is your function's responsibility to pass the values resolved by the promise back to the generator. If the promise rejects, your function should throw that error back to the generator.
6+
If the cancel callback is called before the generator is done, your function should throw an error back to the generator. That error should be the string `"Cancelled"` (Not an `Error` object). If the error was caught, the returned promise should resolve with the next value that was yielded or returned. Otherwise, the promise should reject with the thrown error. No more code should be executed.
7+
8+
When the generator is done, the promise your function returned should resolve the value the generator returned. If, however, the generator throws an error, the returned promise should reject with the error.
9+
10+
An example of how your code would be used:
11+
```javascript
12+
function* tasks() {
13+
const val = yield new Promise(resolve => resolve(2 + 2));
14+
yield new Promise(resolve => setTimeout(resolve, 100));
15+
return val + 1; // calculation shouldn't be done.
16+
}
17+
const [cancel, promise] = cancellable(tasks());
18+
setTimeout(cancel, 50);
19+
promise.catch(console.log); // logs "Cancelled" at t=50ms
20+
```
21+
If instead `cancel()` was not called or was called after `t=100ms`, the promise would have resolved 5.
22+
23+
24+
## Example 1:
25+
26+
Input:
27+
```javascript
28+
generatorFunction = function*() {
29+
return 42;
30+
}
31+
cancelledAt = 100
32+
```
33+
**Output:** `{"resolved": 42}`<br>
34+
**Explanation:**
35+
```javascript
36+
const generator = generatorFunction();
37+
const [cancel, promise] = cancellable(generator);
38+
setTimeout(cancel, 100);
39+
promise.then(console.log); // resolves 42 at t=0ms
40+
```
41+
The generator immediately yields 42 and finishes. Because of that, the returned promise immediately resolves 42. Note that cancelling a finished generator does nothing.
42+
43+
## Example 2:
44+
45+
Input:
46+
```javascript
47+
generatorFunction = function*() {
48+
const msg = yield new Promise(res => res("Hello"));
49+
throw `Error: ${msg}`;
50+
}
51+
cancelledAt = null
52+
```
53+
**Output:** `{"rejected": "Error: Hello"}`<br>
54+
**Explanation:**
55+
A promise is yielded. The function handles this by waiting for it to resolve and then passes the resolved value back to the generator. Then an error is thrown which has the effect of causing the promise to reject with the same thrown error.
56+
57+
## Example 3:
58+
59+
Input:
60+
```javascript
61+
generatorFunction = function*() {
62+
yield new Promise(res => setTimeout(res, 200));
63+
return "Success";
64+
}
65+
cancelledAt = 100
66+
```
67+
**Output:** `{"rejected": "Cancelled"}`<br>
68+
**Explanation:**
69+
While the function is waiting for the yielded promise to resolve, cancel() is called. This causes an error message to be sent back to the generator. Since this error is uncaught, the returned promise rejected with this error.
70+
71+
## Constraints:
72+
73+
`cancelledAt == null or 0 <= cancelledAt <= 1000`<br>
74+
`generatorFunction` returns a generator object

L-A/0011 The Fiscal Code/README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# The Fiscal Code
2+
**[Edabit Problem](https://edabit.com/challenge/Pa2rHJ6KeRBTF28Pg)**
3+
4+
Each person in Italy has an unique identifying ID code issued by the national tax office after the birth registration: the Fiscal Code ([Codice Fiscale](https://en.wikipedia.org/wiki/Italian_fiscal_code_card)).
5+
6+
Given an object containing the personal data of a person (name, surname, gender and date of birth) return the 11 code characters as a string following these steps:
7+
8+
- Generate 3 capital letters from the surname, if it has:
9+
10+
- At least 3 consonants then the first three consonants are used. (Newman -> NWM).
11+
- Less than 3 consonants then vowels will replace missing characters in the same order they appear (Fox -> FXO | Hope -> HPO).
12+
- Less than three letters then "X" will take the third slot after the consonant and the vowel (Yu -> YUX).
13+
14+
- Generate 3 capital letters from the name, if it has:
15+
16+
- Exactly 3 consonants then consonants are used in the order they appear (Matt -> MTT).
17+
- More than 3 consonants then first, third and fourth consonant are used (Samantha -> SNT | Thomas -> TMS).
18+
- Less than 3 consonants then vowels will replace missing characters in the same order they appear (Bob -> BBO | Paula -> PLA).
19+
- Less than three letters then "X" will take the the third slot after the consonant and the vowel (Al -> LAX).
20+
21+
- Generate 2 numbers, 1 letter and 2 numbers from date of birth and gender:
22+
23+
- Take the last two digits of the year of birth (1985 -> 85).
24+
- Generate a letter corresponding to the month of birth (January -> A | December -> T) using the table for conversion included in the code.
25+
- For males take the day of birth adding one zero at the start if is less than 10 (any 9th day -> 09 | any 20th day -> 20).
26+
- For females take the day of birth and sum 40 to it (any 9th day -> 49 | any 20th day -> 60).
27+
28+
### Examples:
29+
30+
```javascipt
31+
fiscalCode({
32+
name: "Matt",
33+
surname: "Edabit",
34+
gender: "M",
35+
dob: "1/1/1900"
36+
}) ➞ "DBTMTT00A01"
37+
38+
fiscalCode({
39+
name: "Helen",
40+
surname: "Yu",
41+
gender: "F",
42+
dob: "1/12/1950"
43+
}) ➞ "YUXHLN50T41"
44+
45+
fiscalCode({
46+
name: "Mickey",
47+
surname: "Mouse",
48+
gender: "M",
49+
dob: "16/1/1928"
50+
}) ➞ "MSOMKY28A16"
51+
```
52+
53+
**Notes:**
54+
- Code letters must be uppercase.
55+
- Date of birth is given in D/M/YYYY format.
56+
- The conversion table for months is already in the starting code.
57+
- Y is not a vowel.
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
function fiscalCode(data) {
2+
const monthsConversion = {
3+
'01': 'A', '02': 'B', '03': 'C', '04': 'D', '05': 'E', '06': 'H',
4+
'07': 'L', '08': 'M', '09': 'P', '10': 'R', '11': 'S', '12': 'T'
5+
};
6+
7+
// Helper function to generate code for names and surnames
8+
function generateCode(name, isSurname) {
9+
const vowels = 'AEIOU';
10+
let consonants = '';
11+
let code = '';
12+
13+
// Helper function to check if a character is a consonant
14+
function isConsonant(char) {
15+
return /[BCDFGHJKLMNPQRSTVWXYZ]/.test(char);
16+
}
17+
18+
for (let i = 0; i < name.length && consonants.length < 3; i++) {
19+
const char = name[i].toUpperCase();
20+
if (isConsonant(char)) {
21+
consonants += char;
22+
}
23+
}
24+
25+
if (consonants.length < 3) {
26+
for (let i = 0; i < name.length && consonants.length < 3; i++) {
27+
const char = name[i].toUpperCase();
28+
if (vowels.includes(char)) {
29+
consonants += char;
30+
}
31+
}
32+
}
33+
34+
if (consonants.length < 3) {
35+
consonants += 'X'.repeat(3 - consonants.length);
36+
}
37+
38+
code = consonants;
39+
40+
if (isSurname) {
41+
code += 'XXX';
42+
} else {
43+
code += name.length >= 3 ? name[0] + name[2] + name[3] : name + 'XX';
44+
}
45+
46+
return code;
47+
}
48+
49+
const surnameCode = generateCode(data.surname, true);
50+
const nameCode = generateCode(data.name, false);
51+
52+
const year = data.dob.split('/')[2].slice(-2);
53+
const month = monthsConversion[data.dob.split('/')[1]];
54+
const day = (data.gender === 'F' ? 40 + parseInt(data.dob.split('/')[0]) : parseInt(data.dob.split('/')[0])).toString().padStart(2, '0');
55+
56+
return `${surnameCode}${nameCode}${year}${month}${day}`;
57+
}
58+
59+
// Examples
60+
console.log(fiscalCode({
61+
name: "Matt",
62+
surname: "Edabit",
63+
gender: "M",
64+
dob: "1/1/1900"
65+
})); // ➞ "DBTMTT00A01"
66+
67+
console.log(fiscalCode({
68+
name: "Helen",
69+
surname: "Yu",
70+
gender: "F",
71+
dob: "1/12/1950"
72+
})); // ➞ "YUXHLN50T41"
73+
74+
console.log(fiscalCode({
75+
name: "Mickey",
76+
surname: "Mouse",
77+
gender: "M",
78+
dob: "16/1/1928"
79+
})); // ➞ "MSOMKY28A16"

L-B/0025 Seven Boom!/README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Seven Boom!
2+
[Edabit Problem](https://edabit.com/challenge/6R6gReGTGwzpwuffD)
3+
4+
Create a function that takes an array of numbers and return `"Boom!"` if the digit 7 appears in the array. Otherwise, return `"there is no 7 in the array"`.
5+
6+
Examples:
7+
```javascript
8+
sevenBoom([1, 2, 3, 4, 5, 6, 7]) ➞ "Boom!"
9+
// 7 contains the number seven.
10+
11+
sevenBoom([8, 6, 33, 100]) ➞ "there is no 7 in the array"
12+
// None of the items contain 7 within them.
13+
14+
sevenBoom([2, 55, 60, 97, 86]) ➞ "Boom!"
15+
// 97 contains the number seven.
16+
```
17+

L-B/0025 Seven Boom!/SevenBoom.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
function sevenBoom(arr) {
2+
for (let i = 0; i < arr.length; i++) {
3+
if (String(arr[i]).includes('7')) {
4+
return 'Boom!';
5+
}
6+
}
7+
return 'there is no 7 in the array';
8+
}

0 commit comments

Comments
 (0)