Guest User

Untitled

a guest
May 27th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.45 KB | None | 0 0
  1. // ================================================================================
  2. // You will be writing a series of functions beneath each block of comments below.
  3. // Tackle each function one at a time. You may move on to a new exercise and return
  4. // later. Run the code and the console to the right will tell you if your function
  5. // is successfully passing the tests.
  6. // ================================================================================
  7.  
  8.  
  9. /*
  10. Define a function named `kmToMiles` that receives one parameter:
  11. 1) km - type: number
  12. The function should return a number in miles, rounded down to nearest integer.
  13. function
  14.  
  15. HINT: There are 1.6km in 1 mile.
  16. HINT: What method on Javascript's Math object can round decimals down to nearest whole number?
  17. */
  18. function kmToMiles(km){
  19. return Math.round(km/1.6);
  20.  
  21. }
  22.  
  23. /*
  24. Define a function named `countLetters` that receives two parameters:
  25. 1) sentence - type: string
  26. 2) character - type: string
  27. The function should return a count of every `character` present in `sentence`.
  28.  
  29. HINT: You can access a single character in a string just like accessing an element in an array - `myString[3]` would access the fourth character
  30. */
  31. function countLetters(sent1, chara){
  32. let tempNum = 0;
  33. let str = sent1.split("");
  34. for (let i = 0; i < str.length; i++){
  35. if (str[i] === chara){
  36. tempNum++;
  37. }
  38. }
  39. return tempNum;
  40. }
  41.  
  42. /*
  43. Define a function named `middleElement` that receives one parameter:
  44. 1) items - type: array
  45. The function should return the element present in the middle index. If
  46. the array contains an even number of elements, return the item in the
  47. first half of the array closest to the middle.
  48.  
  49. HINT: You can use the expression `n % 2 === 0` to check if `n` is an even number
  50. */
  51. function middleElement(arr){
  52. if(arr.length % 2 === 0){
  53. let tempNum1 = arr.length/2;
  54. return arr[tempNum1-1];
  55. }
  56. else {
  57. let tempNum = Math.round(arr.length/2);
  58. return arr[tempNum - 1];
  59. }
  60. }
  61.  
  62. /*
  63. Define a function named `rightToVote` that receives one parameter:
  64. 1) person - type: object
  65. The function should check the `age` property on `person`. If it is 18 or older,
  66. return true. Otherwise, return false. If `age` is not a number, throw an error.
  67.  
  68. HINT: The `typeof` operator can tell you what data type a variable is
  69. */
  70. function rightToVote(person){
  71. if(typeof person.age !== "number"){
  72. throw "This age is not a number.";
  73. }
  74. if(person.age >= 18){
  75. return true;
  76. }
  77. else {
  78. return false;
  79. }
  80. }
  81.  
  82. /*
  83. Define a factory function `createStudent` that receives two parameters:
  84. 1) name - type: string
  85. 2) location - type: string
  86. This factory should return an object that includes the provided `name` and `location`
  87. properties and also has a `describe` method that returns the string: "Hello, I
  88. am {name} and I live in {location}."
  89.  
  90. HINT: You will want to use the `this` keyword
  91. */
  92. function createStudent(name, loc){
  93. let studentObj = {
  94. name: name,
  95. location: loc,
  96. describe: function(){
  97. return `Hello, I am ${this.name} and I live in ${this.location}.`;
  98.  
  99. }
  100. };
  101. return studentObj;
  102. }
  103.  
  104.  
  105.  
  106. /*
  107. ===========================================
  108. IGNORE ALL CODE BELOW HERE
  109. ===========================================
  110. |
  111. |
  112. |
  113. |
  114. |
  115. |
  116. |
  117. |
  118. */
  119. /* eslint-disable no-console */
  120. (function(){
  121. function fnExists(fnName) {
  122. return window[fnName] !== undefined;
  123. }
  124.  
  125. function testKmToMiles() {
  126. const FN_NAME = 'kmToMiles';
  127. if (!fnExists(FN_NAME))
  128. return console.log(`\`${FN_NAME}\` - FAIL: function is not defined`);
  129.  
  130. const results = [];
  131. const testArgs = [50, 79];
  132. const expected = [31, 49];
  133.  
  134. try {
  135. testArgs.forEach(ta => results.push(window[FN_NAME](ta)));
  136. } catch(e) {
  137. return console.log(`\`${FN_NAME}\` - FAIL: function produced unexpected error: ${e.message}`);
  138. }
  139.  
  140. for (let i = 0; i < results.length; i++) {
  141. if (results[i] !== expected[i]) {
  142. return console.log(`\`${FN_NAME}(${testArgs[i]})\` - FAIL: expected ${expected[i]}, got ${results[i]}`);
  143. }
  144. }
  145.  
  146. console.log(`\`${FN_NAME}\` - SUCCESS: All tests passed`);
  147. }
  148.  
  149. function testCountLetters() {
  150. const FN_NAME = 'countLetters';
  151. if (!fnExists(FN_NAME))
  152. return console.log(`\`${FN_NAME}\` - FAIL: function is not defined`);
  153.  
  154. const results = [];
  155. const testArgs = [
  156. ['fly me to the moon', 'o'],
  157. ['do or do not. there is no try', 'e']
  158. ];
  159. const expected = [3, 2];
  160.  
  161. try {
  162. testArgs.forEach(ta => results.push(window[FN_NAME](...ta)));
  163. } catch(e) {
  164. return console.log(`\`${FN_NAME}\` - FAIL: function produced unexpected error: ${e.message}`);
  165. }
  166.  
  167. for (let i = 0; i < results.length; i++) {
  168. if (results[i] !== expected[i]) {
  169. return console.log(`\`${FN_NAME}(${testArgs[i].map(e => `'${e}'`).join(', ')})\` - FAIL: expected ${expected[i]}, got ${results[i]}`);
  170. }
  171. }
  172.  
  173. console.log(`\`${FN_NAME}\` - SUCCESS: All tests passed`);
  174. }
  175.  
  176. function testMiddleElement() {
  177. const FN_NAME = 'middleElement';
  178. if (!fnExists(FN_NAME))
  179. return console.log(`\`${FN_NAME}\` - FAIL: function is not defined`);
  180.  
  181. const results = [];
  182. const testArgs = [
  183. [2,5,7,10,34],
  184. [2,5,10,34]
  185. ];
  186. const expected = [7, 5];
  187.  
  188. try {
  189. testArgs.forEach(ta => results.push(window[FN_NAME](ta)));
  190. } catch(e) {
  191. return console.log(`\`${FN_NAME}\` - FAIL: function produced unexpected error: ${e.message}`);
  192. }
  193.  
  194. for (let i = 0; i < results.length; i++) {
  195. if (results[i] !== expected[i]) {
  196. return console.log(`\`${FN_NAME}([${testArgs[i]}])\` - FAIL: expected ${expected[i]}, got ${results[i]}`);
  197. }
  198. }
  199.  
  200. console.log(`\`${FN_NAME}\` - SUCCESS: All tests passed`);
  201. }
  202.  
  203. function testRightToVote() {
  204. const FN_NAME = 'rightToVote';
  205. const fn = window[FN_NAME];
  206. if (!fnExists(FN_NAME))
  207. return console.log(`\`${FN_NAME}\` - FAIL: function is not defined`);
  208.  
  209. const results = [];
  210. const testArgs = [
  211. { name: 'rich', age: 25 },
  212. { name: 'rich', age: 15 },
  213. { name: 'john', age: 18 }
  214. ];
  215. const expected = [true, false, true];
  216.  
  217. try {
  218. testArgs.forEach(ta => results.push(window[FN_NAME](ta)));
  219. } catch(e) {
  220. return console.log(`\`${FN_NAME}\` - FAIL: function produced unexpected error: ${e.message}`);
  221. }
  222.  
  223. for (let i = 0; i < results.length; i++) {
  224. if (results[i] !== expected[i]) {
  225. return console.log(`\`${FN_NAME}(${JSON.stringify(testArgs[i])})\` - FAIL: expected ${expected[i]}, got ${results[i]}`);
  226. }
  227. }
  228.  
  229. // Custom tests
  230. let result1, result2;
  231. try {
  232. result1 = fn({ name: 'rich', age: undefined });
  233. return console.log(`\`${FN_NAME}\` - FAIL: expected error to be thrown when 'age' not a number`);
  234. } catch(e) {
  235. // Successful test if error thrown... caveat: not testing for specific error
  236. }
  237.  
  238. console.log(`\`${FN_NAME}\` - SUCCESS: All tests passed`);
  239. }
  240.  
  241. function testCreateStudent() {
  242. const FN_NAME = 'createStudent';
  243. const fn = window[FN_NAME];
  244. if (!fnExists(FN_NAME))
  245. return console.log(`\`${FN_NAME}\` - FAIL: function is not defined`);
  246.  
  247. let result1;
  248. try {
  249. result1 = fn('Rich', 'Los Angeles');
  250. } catch(e) {
  251. return console.log(`\`${FN_NAME}\` - FAIL: function produced unexpected error: ${e.message}`);
  252. }
  253.  
  254. let failMsg = (msg) => `\`${FN_NAME}('Rich', 'Los Angeles')\` - FAIL: ${msg}`;
  255.  
  256. if (typeof result1 !== 'object')
  257. return console.log(failMsg('did not return an object'));
  258. if (result1.name !== 'Rich')
  259. return console.log(failMsg(`expected prop 'name' to be 'Rich', instead got '${result1.name}'`));
  260. if (result1.location !== 'Los Angeles')
  261. return console.log(failMsg(`expected prop 'location' to be 'Los Angeles', instead got '${result1.location}'`));
  262. if (typeof result1.describe !== 'function')
  263. return console.log(failMsg('expected prop \'describe\' to be a function'));
  264. if (result1.describe() !== 'Hello, I am Rich and I live in Los Angeles.')
  265. return console.log(failMsg('\'describe\' method did not return correct message'));
  266.  
  267. result1.name = 'Joe';
  268. if (result1.describe() !== 'Hello, I am Joe and I live in Los Angeles.')
  269. return console.log(failMsg('\'describe\' method did not return correct message. Are you using `this` correctly?'));
  270.  
  271. console.log(`\`${FN_NAME}\` - SUCCESS: All tests passed`);
  272. }
  273.  
  274.  
  275. testKmToMiles();
  276. testCountLetters();
  277. testMiddleElement();
  278. testRightToVote();
  279. testCreateStudent();
  280. }());
Add Comment
Please, Sign In to add comment