Advertisement
armandocat

Coding challenge #2

Sep 15th, 2017
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. function reverseRecursive(obj) {
  3.   return obj;
  4. }
  5.  
  6. function reverseIterative(obj) {
  7.   return obj;
  8. }
  9.  
  10.  
  11. /***************************/
  12. /***************************/
  13. /* DO NOT CHANGE DOWN HERE */
  14. /***************************/
  15. /***************************/
  16.  
  17.  
  18. function Obj(v, next) {
  19.   this.v = v;
  20.   this.next = next;
  21. }
  22. Obj.prototype.toString = function() {
  23.   var next = this.next ? ' -> ' + this.next.toString() : '';
  24.   return this.v + next;
  25. };
  26. Obj.prototype.clone = function() {
  27.   return new Obj(this.v, this.next && this.next.clone());
  28. };
  29.  
  30. function arrayToObj(array) {
  31.   var obj;
  32.   for (var i = array.length - 1; i >= 0; i--) {
  33.     obj = new Obj(array[i], obj);
  34.   }  
  35.   return obj;
  36. }
  37.  
  38.  
  39.  
  40. function test(array) {
  41.   var obj = arrayToObj(array);
  42.   console.log('Original:')
  43.   console.log(obj && obj.toString());
  44.  
  45.   var r1 = reverseRecursive(obj && obj.clone());
  46.   console.log('Reversed (recursive algorithm):');
  47.   console.log(r1 && r1.toString());
  48.  
  49.   var r2 = reverseIterative(obj && obj.clone());
  50.   console.log('Reversed (iterative algorithm):');
  51.   console.log(r2 && r2.toString());
  52.  
  53.   console.log();
  54. }
  55.  
  56. test([1, 2, 3, 4, 5, 6]);
  57. test([1]);
  58. test([]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement