Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Make a function diceThrow, that returns a Promise. After a random duration of up to 2 seconds, this Promise should print a random integer between 1 and 6, and then resolve with this integer as result. */
- function diceThrow() {
- return new Promise(function (res, rej) {
- let dice = Math.random() * (6 - 1) + 1;
- function throw() {
- if (dice > 0 && dice < 7) res(dice);
- else if (dice === 0 || dice > 6) rej('Invalid!');
- }
- });
- }
- diceThrow(1)
- .then((resultat) => {
- console.log('Resultat: ' + resultat); return terningKast(2);
- })
- .then((resultat) => console.log('Resultat: ' + resultat))
- .catch((fejl) => console.log('Fejl: ' + fejl));
- /* Make a function throwTwoDice, that uses diceThrow to throw two dice. If the two dice are the same, it should print 'won!', otherwise it should print 'lost!' */
- function throwTwoDice1() {
- const dice1 = diceThrow();
- const dice2 = diceThrow();
- if (dice1 === dice2) return 'Won!';
- else return 'Lost!';
- }
- /* The function throwTwoDice must be implemented in two ways - one with, and the other without, use of async and await. */
- async function throwTwoDice2() {
- let dice1 = await diceThrow();
- let dice2 = await diceThrow();
- if (dice1 === dice2) return 'Won!';
- else return 'Lost!';
- }
- /* ------------------- */
- /* Make a function lessThan(a,b) with two parameters. The function must return a boolean, that tells whether or not a is less than b. The function must be able to compare to numbers or two strings. The function must throw an exception, if the two parameters are different from the above. */
- function lessThan(a, b) {
- if (typeof (a) == Number && typeof (b) == Number || typeof (a) == String && typeof (b) == String) {
- return a < b;
- } else {
- throw 'a & b must be the same!';
- }
- }
- /* Test the function. */
- console.log(lessThan(3, 7));
- console.log(lessThan("a", "b"));
- console.log(lessThan(9, 7));
- console.log(lessThan("f", "b"));
- console.log(lessThan(17, "b"));
- /* Make an array with some numbers, and use the function lessThan, and a for-loop, to find the smallest number in the array. */
- let arr = [2, 7, 3, 17, 42];
- let x = Math.max
- for (let i = 0; i < arr.length - 1; i++) {
- if (arr[i] < x) {
- x = arr[i];
- }
- }
- /* Then make an array with some strings and use the function lessThan, and the method reduce, on the array to find the smallest string in the array. */
- let strArr = ['abc', 'ghi', 'def', 'jkl'];
- let toReturn = strArr.reduce(function (strs, val, index) {
- let sep = strArr.length ? ", " : "";
- return strs + sep + val;
- }, '');
Advertisement
Add Comment
Please, Sign In to add comment