Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Friday Programming Quiz

Friday Programming Quiz

Scheduled Pinned Locked Moved The Lounge
csharpasp-netcomhelptutorial
32 Posts 14 Posters 5 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Shog9 0

    [] is an empty array. In this case, i'm using it as shorthand for Array.prototype. Why? Because arguments isn't actually a proper array - while it does array-like things (indexed access to the current function's parameters), it's a separate type of object, one that also does other, function-specific things. So, it doesn't have a slice() method, which i wanted - slice() extracts a portion of an array (i want the second item and everything after it). call() and apply() are members of every function. call() takes at least one argument, which will become this when the function executes, while each subsequent argument becomes an argument to the function itself. In this way, i can call a function defined for Array objects on an arbitrary array-like object (arguments) and everything works just fine. apply() is very similar to call(), except that it takes two parameters, with the second being an array of arguments to the function. In this way, Transact() handles recursion with a variable (but ever-decreasing) number of arguments. A simpler definition for Transact might look like this:

    function Transact(ops)
    {
    if ( ops.length < 1 )
    return true;
    var op = ops[0];
    if ( op() && Transact(ops.slice(1)) )
    return true;
    eval("Reset"+op.name)();
    return false;
    }

    Transact([Step1, Step2, Step3, Step4]);

    ...while a slightly more confusing implementation could take this form:

    function Transact()
    {
    if ( arguments.length < 1 )
    return true;
    var op = arguments[0];
    if ( op() && arguments.callee.apply(this, [].slice.call(arguments, 1)) )
    return true;
    eval("Reset"+op.name)();
    return false;
    }

    ;)

    ----

    I don't care what you consider witty, but at least I do not blather on posting nonsense like Jim Crafton.

    -- Stringcheese, humbled by Crafton's ability to string together multiple sentences

    J Offline
    J Offline
    Josh Smith
    wrote on last edited by
    #20

    Shog9 wrote:

    call() and apply() are members of every function.

    I'm still shocked by this. In Javascript, functions have members. That is very strange to me, coming from a "classical" object-oriented background of C++ and C#. Do you commonly find a use for the members of functions, or is it an abstruse niche that you happen to be savvy about?

    :josh: My WPF Blog[^] Without a strive for perfection I would be terribly bored.

    S 1 Reply Last reply
    0
    • G Gary R Wheeler

      In the K.I.S.S. tradition:

      void (*step[])() = { Step1, Step2, Step3, Step4, Step5 };
      void (*reset_step[])() = { ResetStep1, ResetStep2, ResetStep3, ResetStep4, ResetStep5 };

      int index = 0;
      int step_count = sizeof(step) / sizeof(step[0]);

      while ((index < step_count) && step[index]()) index++;
      if (index < step_count) {
      while (index >= 0) reset_step[--index];
      }


      Software Zen: delete this;

      Fold With Us![^]

      S Offline
      S Offline
      Shog9 0
      wrote on last edited by
      #21

      Nice! (missing parens in the call to reset though)

      ----

      I don't care what you consider witty, but at least I do not blather on posting nonsense like Jim Crafton.

      -- Stringcheese, humbled by Crafton's ability to string together multiple sentences

      1 Reply Last reply
      0
      • J Josh Smith

        Shog9 wrote:

        call() and apply() are members of every function.

        I'm still shocked by this. In Javascript, functions have members. That is very strange to me, coming from a "classical" object-oriented background of C++ and C#. Do you commonly find a use for the members of functions, or is it an abstruse niche that you happen to be savvy about?

        :josh: My WPF Blog[^] Without a strive for perfection I would be terribly bored.

        S Offline
        S Offline
        Shog9 0
        wrote on last edited by
        #22

        It's just part of how Javascript works - there isn't the same distinction between functions, classes, and objects that you get with, say, C++. All functions are objects, derived from Function and inheriting whatever methods are defined for it. You can actually add methods to Function and immediately use them on any other function (this also works for other base types such as Array and Object; it's great for filling in the gaps of a sub-par (*cough*IE*cough*) JS engine). And you make your own types by - wait for it - defining a function that creates them! That said, you don't really get things like inheritance in the classical sense, although the language is flexible enough you can make it work with a bit of discipline. Honestly, it's a lot of fun. ;)

        ----

        I don't care what you consider witty, but at least I do not blather on posting nonsense like Jim Crafton.

        -- Stringcheese, humbled by Crafton's ability to string together multiple sentences

        J 1 Reply Last reply
        0
        • S Shog9 0

          It's just part of how Javascript works - there isn't the same distinction between functions, classes, and objects that you get with, say, C++. All functions are objects, derived from Function and inheriting whatever methods are defined for it. You can actually add methods to Function and immediately use them on any other function (this also works for other base types such as Array and Object; it's great for filling in the gaps of a sub-par (*cough*IE*cough*) JS engine). And you make your own types by - wait for it - defining a function that creates them! That said, you don't really get things like inheritance in the classical sense, although the language is flexible enough you can make it work with a bit of discipline. Honestly, it's a lot of fun. ;)

          ----

          I don't care what you consider witty, but at least I do not blather on posting nonsense like Jim Crafton.

          -- Stringcheese, humbled by Crafton's ability to string together multiple sentences

          J Offline
          J Offline
          Josh Smith
          wrote on last edited by
          #23

          Shog9 wrote:

          And you make your own types by - wait for it - defining a function that creates them!

          :wtf: Do Javascript developers have to drink the special Kool-aid before being "initiated"??? :)

          Shog9 wrote:

          Honestly, it's a lot of fun.

          Sounds like it.

          :josh: My WPF Blog[^] Without a strive for perfection I would be terribly bored.

          S 1 Reply Last reply
          0
          • J Josh Smith

            Shog9 wrote:

            And you make your own types by - wait for it - defining a function that creates them!

            :wtf: Do Javascript developers have to drink the special Kool-aid before being "initiated"??? :)

            Shog9 wrote:

            Honestly, it's a lot of fun.

            Sounds like it.

            :josh: My WPF Blog[^] Without a strive for perfection I would be terribly bored.

            S Offline
            S Offline
            Shog9 0
            wrote on last edited by
            #24

            :) Btw - if you're interested, check out this link[^]. He demonstrates most of what i was talking about, and does a better job of explaining it.

            ----

            I don't care what you consider witty, but at least I do not blather on posting nonsense like Jim Crafton.

            -- Stringcheese, humbled by Crafton's ability to string together multiple sentences

            J 2 Replies Last reply
            0
            • S Shog9 0

              :) Btw - if you're interested, check out this link[^]. He demonstrates most of what i was talking about, and does a better job of explaining it.

              ----

              I don't care what you consider witty, but at least I do not blather on posting nonsense like Jim Crafton.

              -- Stringcheese, humbled by Crafton's ability to string together multiple sentences

              J Offline
              J Offline
              Josh Smith
              wrote on last edited by
              #25

              Shog9 wrote:

              if you're interested, check out this link[^].

              Thanks, I'll check it out. Going to see some apartments now (sigh).

              :josh: My WPF Blog[^] Without a strive for perfection I would be terribly bored.

              1 Reply Last reply
              0
              • A Anton Afanasyev

                bool DoSteps(IEnumerable steps)
                {
                Step step=steps.FirstOrDefault();
                if(step==null || (step.Action() && DoSteps(steps.TakeAfter(0))))
                return true;
                step.Reset();
                return false;
                }

                could be changed to:

                bool DoSteps(IEnumerable steps)
                {
                Step step=steps.FirstOrDefault();
                return (step==null || (step.Action() && DoSteps(steps.TakeAfter(0)))|| (step.Reset() && false));
                }

                and btw, you forget a bracket there ;)


                :badger:

                J Offline
                J Offline
                J Dunlap
                wrote on last edited by
                #26

                Anton Afanasyev wrote:

                could be changed to: [...]

                Yeah... but it's less readable. ;)

                Anton Afanasyev wrote:

                and btw, you forget a bracket there ;)

                Oops! :-O

                --Justin, Microsoft MVP, C#

                C# / DHTML / VG.net / MyXaml expert available for consulting work[^] Get Quality Portraits Drawn From Your Photos[^]

                1 Reply Last reply
                0
                • G Gary R Wheeler

                  Teach me not to read the whole thread... :-O Aha! Your solution doesn't work quite correctly. It will never call ResetStep1().


                  Software Zen: delete this;

                  Fold With Us![^]

                  I Offline
                  I Offline
                  ied
                  wrote on last edited by
                  #27

                  Sure it does (I tested it). It predecrements the index before calling the resetstep function, so when i=1 it calls resetstep1. -- Ian

                  1 Reply Last reply
                  0
                  • S Shog9 0

                    :) Btw - if you're interested, check out this link[^]. He demonstrates most of what i was talking about, and does a better job of explaining it.

                    ----

                    I don't care what you consider witty, but at least I do not blather on posting nonsense like Jim Crafton.

                    -- Stringcheese, humbled by Crafton's ability to string together multiple sentences

                    J Offline
                    J Offline
                    Josh Smith
                    wrote on last edited by
                    #28

                    Shog9 wrote:

                    He demonstrates most of what i was talking about, and does a better job of explaining it.

                    That's a very clear explanation of how JavaScript provides OO. I thought the prototype idea was cool, but using it seems rather verbose. The one thing I wasn't impressed by is JavaScript's support for, or maybe just his example of, polymorphism. What he demonstrated is not really polymorphism, but just calling functions on two objects that happen to have the same name and parameter list. No virtual/override was involved, so it's not truly polymorphic from the caller's perspective. Here's the example:

                    function A(){this.x = 1;}
                    A.prototype.DoIt = function()
                    // Define Method
                    {this.x += 1;}

                    function B(){this.x = 1;}
                    B.prototype.DoIt = function()
                    // Define Method
                    {this.x += 2;}

                    a = new A;
                    b = new B;
                    a.DoIt();
                    b.DoIt();
                    document.write(a.x + ', ' + b.x);

                    :josh: My WPF Blog[^] Without a strive for perfection I would be terribly bored.

                    R 1 Reply Last reply
                    0
                    • R Rama Krishna Vavilala

                      A common problem, a simple problem of compensating transactions. There are variety of different solutions. There are 5 steps an application need to perform in sequence. Call them Step1, Step2, Step3, Step4, and Step5. Assume them to be functions that return boolean and take no arguments. bool Step() There are corresponding reset or rollback functions that undo the effects of the steps. Call them ResetStep1, ResetStep2, ResetStep3, ResetStep4, and ResetStep5. If a step fails, the Reset methods of all the previous steps should be called and none of the new steps should execute. For example, if Step3 fails (returns false), then ResetStep2() and ResetStep1() should be called (in that order). Here is a sample code written poorly so that you can get an idea. BTW There are several creatve solutions: RAII, boolean algebra etc.

                      if (Step1())
                      {
                      if (Step2())
                      {
                      if (Step3())
                      {
                      if (Step4())
                      {
                      //.....
                      //You get the idea
                      }
                      else
                      {
                      ResetStep2();
                      ResetStep1();
                      }
                      }
                      else
                      {
                      ResetStep1();
                      }
                      }

                      Co-Author ASP.NET AJAX in Action

                      P Offline
                      P Offline
                      PIEBALDconsult
                      wrote on last edited by
                      #29

                      Rama Krishna Vavilala wrote:

                      Assume them to be functions that return boolean

                      No, I'll insist that they throw an Exception. As such, I'd simply alter the sample to use try/catch rather than if/else.

                      try
                      {
                      Step1() ;

                      try
                      {
                          Step2() ;
                      
                          // etc.
                      }
                      catch ( System.Exception err )
                      {
                          ResetStep1() ;
                          throw ( err ) ;
                      }
                      

                      }
                      catch ( System.Exception err )
                      {
                      // Log message
                      }

                      R P 2 Replies Last reply
                      0
                      • P PIEBALDconsult

                        Rama Krishna Vavilala wrote:

                        Assume them to be functions that return boolean

                        No, I'll insist that they throw an Exception. As such, I'd simply alter the sample to use try/catch rather than if/else.

                        try
                        {
                        Step1() ;

                        try
                        {
                            Step2() ;
                        
                            // etc.
                        }
                        catch ( System.Exception err )
                        {
                            ResetStep1() ;
                            throw ( err ) ;
                        }
                        

                        }
                        catch ( System.Exception err )
                        {
                        // Log message
                        }

                        R Offline
                        R Offline
                        Rama Krishna Vavilala
                        wrote on last edited by
                        #30

                        Well you can wrap the step in an exception throwing function.

                        void StepWithException(Step step)
                        {
                        if (!step())
                        throw new StepFailedException();
                        }

                        Co-Author ASP.NET AJAX in Action

                        1 Reply Last reply
                        0
                        • P PIEBALDconsult

                          Rama Krishna Vavilala wrote:

                          Assume them to be functions that return boolean

                          No, I'll insist that they throw an Exception. As such, I'd simply alter the sample to use try/catch rather than if/else.

                          try
                          {
                          Step1() ;

                          try
                          {
                              Step2() ;
                          
                              // etc.
                          }
                          catch ( System.Exception err )
                          {
                              ResetStep1() ;
                              throw ( err ) ;
                          }
                          

                          }
                          catch ( System.Exception err )
                          {
                          // Log message
                          }

                          P Offline
                          P Offline
                          PIEBALDconsult
                          wrote on last edited by
                          #31

                          As I was finishing up that post I remembered another tactic that I learned while doing embedded PL/SQL in the '90s. Adjusted for C# and again using Exceptions rather than booleans:

                          int step = 0 ;

                          try
                          {
                          Step1() ;
                          step = 1 ;

                          Step2() ;
                          step = 2 ;
                          
                          Step3() ;
                          step = 3 ;
                          
                          Step4() ;
                          step = 4 ;
                          
                          Step5() ;
                          step = 5 ;
                          

                          }
                          catch ( System.Exception err )
                          {
                          // Log message

                          switch ( step )
                          {
                              case 4 : { ResetStep4() ; goto case 3 ; }
                              case 3 : { ResetStep3() ; goto case 2 ; }
                              case 2 : { ResetStep2() ; goto case 1 ; }
                              case 1 : { ResetStep1() ; break       ; }
                          }
                          

                          }

                          1 Reply Last reply
                          0
                          • J Josh Smith

                            Shog9 wrote:

                            He demonstrates most of what i was talking about, and does a better job of explaining it.

                            That's a very clear explanation of how JavaScript provides OO. I thought the prototype idea was cool, but using it seems rather verbose. The one thing I wasn't impressed by is JavaScript's support for, or maybe just his example of, polymorphism. What he demonstrated is not really polymorphism, but just calling functions on two objects that happen to have the same name and parameter list. No virtual/override was involved, so it's not truly polymorphic from the caller's perspective. Here's the example:

                            function A(){this.x = 1;}
                            A.prototype.DoIt = function()
                            // Define Method
                            {this.x += 1;}

                            function B(){this.x = 1;}
                            B.prototype.DoIt = function()
                            // Define Method
                            {this.x += 2;}

                            a = new A;
                            b = new B;
                            a.DoIt();
                            b.DoIt();
                            document.write(a.x + ', ' + b.x);

                            :josh: My WPF Blog[^] Without a strive for perfection I would be terribly bored.

                            R Offline
                            R Offline
                            Rama Krishna Vavilala
                            wrote on last edited by
                            #32

                            It's a different way of inheritance. JavaScript has something called "Prototype based inheritance". It's a different way now you can extend it all the way you want. For example here is one way of doing that: http://www.asp.net/ajax/documentation/live/tutorials/EnhancingJavaScriptTutorial.aspx[^]

                            Co-Author ASP.NET AJAX in Action

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups