SitePoint Sponsor

User Tag List

Results 1 to 23 of 23
  1. #1
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)

    This Week in JavaScript - 7 October 2013

    This is a weekly update of some interesting things relating to JavaScript, to help encourage discussion and to bring some potentially new ideas to the fore.

    Here's what we've seen of interest this week.

    Quiz

    You Can't JavaScript Under Pressure - Five functions to fill. One ticking clock. How fast can you code?
    If I'm completely honest, I needed 17 minutes and five seconds. Who can beat that? (shouldn't be hard ).

    Free Book

    JavaScript Allongé by Reginald Braithwaite is a free book (to read online) that focuses on using functions to write simpler JavaScript with fewer bugs

    Listening

    Chales Max Wood and Joe Eames talk about working from home on the most recent JavaScript Jabber podcast.
    Does anyone reading this work from home? I do, and I love it!

    Code Quality

    JSHint just got a makeover.
    What do you think? Better, worse?

    Libraries

    One Page Scroll - Create an Apple-like one page scroller website (iPhone 5S website) with the One Page Scroll plugin
    Top 5 jQuery UI Alternatives

    Debugging

    The JavaScript console API - An overview of the various methods of the console.


    Take a look at these recent happenings in JavaScript, let us know what you think about them, and we'll have some more to inspire you next week.

    Feel free to PM me or PM Paul if you have anything interesting for the next issue.
    Last edited by Pullo; Oct 8, 2013 at 05:25. Reason: Typo

  2. #2
    SitePoint Zealot daveporter's Avatar
    Join Date
    Mar 2002
    Location
    Perth, Western Australia
    Posts
    133
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Oops! The Free book does not appear to be free (unless you want to read it on-line!)
    Cheers, Dave

  3. #3
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by daveporter View Post
    Oops! The Free book does not appear to be free (unless you want to read it on-line!)
    Thanks for pointing that out, Dave. I amended my post accordingly to reflect that fact.
    It's still a pretty good deal, though

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Has anyone tried You Can't JavaScript Under Pressure yet?

    How did you go?
    Did you (like me) make a couple of runs at it?
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,330
    Mentioned
    463 Post(s)
    Tagged
    8 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    Hehe, I'm still going. It's up to about 56 hours now.

    Well, not being a programmer doesn't help ... and I hate the timer thing, but it's still fun to have a go and learn something. Pullo has also been coaching me along on the sly, too. I'm up to question 4.

  6. #6
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    Did you (like me) make a couple of runs at it?
    Only because in a fit of clumsiness I refreshed my browser half-way through. DOH!

    For me the main sticking point was question 5.

    I'm still helping Ralph with one of these questions (so don't want to give the answer away), but once I've heard back from him maybe we can compare answers / techniques.

  7. #7
    The CSS Clinic is open silver trophybronze trophy
    Paul O'B's Avatar
    Join Date
    Jan 2003
    Location
    Hampshire UK
    Posts
    40,549
    Mentioned
    183 Post(s)
    Tagged
    6 Thread(s)
    Hehe, I'm still going. It's up to about 56 hours now.
    I had a go and managed the first 4 (after a bit of googling) but stuck in a recursive loop on question 5 at the moment.

  8. #8
    The CSS Clinic is open silver trophybronze trophy
    Paul O'B's Avatar
    Join Date
    Jan 2003
    Location
    Hampshire UK
    Posts
    40,549
    Mentioned
    183 Post(s)
    Tagged
    6 Thread(s)
    Quote Originally Posted by Pullo View Post
    I needed 17 minutes and five seconds. Who can beat that? (shouldn't be hard ).
    It took me " 178 minutes, 37 seconds for all 5 levels. Well done! "

    But that did include walking the dog, having lunch, a little bit of work and vast amounts of googling

    I'm not sure my last answer was good coding though so if someone wants to tidy it up and point out the errors it would be appreciated.


    //test5
    var total=0;
    function arraySum(i) {

    // i will be an array, containing integers, strings and/or arrays like itself.
    // Sum all the integers you find, anywhere in the nest of arrays.
    for (var loop= 0; loop < i.length; loop++)
    {
    // check if it is an array
    if (i[loop] instanceof Array) {
    var nested = i[loop];
    arraySum(nested);
    }
    // check if a number
    if (typeof i[loop] == "number"){
    total= total + i[loop];
    }
    }
    return total;
    }


  9. #9
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi Paul,

    That's exactly how I did it, except that you can eliminate the need for the global variable like so:

    function arraySum(i) {
    var total = 0;
    for (var loop= 0; loop < i.length; loop++){
    // check if it is an array
    if (i[loop] instanceof Array) {
    var nested = i[loop];
    total += arraySum(nested);
    }

    // check if a number
    if (typeof i[loop] == "number"){
    total += i[loop];
    }
    }
    return total;
    }


    I only had to check Google for the syntax of one particular method, so I was quite pleased with that.
    I'll post the rest of my answers later and we can compare

  10. #10
    The CSS Clinic is open silver trophybronze trophy
    Paul O'B's Avatar
    Join Date
    Jan 2003
    Location
    Hampshire UK
    Posts
    40,549
    Mentioned
    183 Post(s)
    Tagged
    6 Thread(s)
    Quote Originally Posted by Pullo View Post
    Hi Paul,
    That's exactly how I did it, except that you can eliminate the need for the global variable like so:
    I always have trouble with global variables

    It took me a while to work out what you had done here:


    total += arraySum(nested);



    But I finally realised that the array was returning the value of the total so it wasn't lost when it was set to zero at the beginning of the function.

    These were my answers for tests 2 - 4:



    //test 2
    function isNumberEven(i) {
    // i will be an integer. Return true if it's even, and false if it isn't.
    return (i%2 == 0) ? true : false;
    }
    // test 3
    function getFileExtension(i) {
    // i will be a string, but it may not have a file extension.
    // return the file extension (with no period) if it has one, otherwise false
    var has_dot = false;
    has_dot = i.indexOf('.');
    if (has_dot > -1){
    return i.substr(i.lastIndexOf('.') + 1)
    }
    return false;
    }
    // test 3
    function getFileExtension(i) {
    // i will be a string, but it may not have a file extension.
    // return the file extension (with no period) if it has one, otherwise false
    var has_dot = false;
    has_dot = i.indexOf('.');
    if (has_dot > -1){
    return i.substr(i.lastIndexOf('.') + 1)
    }
    return false;
    }
    //test4
    function longestString(i) {
    // i will be an array.
    // return the longest string in the array
    var longest = 0;
    var longstring = 0;
    for (var l=0; l < i.length; l++)
    {
    if (i[l].length > longest && typeof i[l] == "string") {
    longest = i[l].length;
    longstring = l;
    }
    }
    return i[longstring];
    }





    Any tips, improvements or suggestions welcomed

  11. #11
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    I ended up having syntax issues when using typeof and blanked on instanceof, so a different solution was used by me.
    Now that I know that they do work, I'll take another run at things later.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  12. #12
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    So, the first two are no brainers:

    Code JavaScript:
    function doubleInteger(i) {
      // i will be an integer. Double it and return it.
      return i*2;
    }

    Code JavaScript:
    function isNumberEven(i) {
      // i will be an integer. Return true if it's even, and false if it isn't.
      return i%2 === 0;   
    }

    With three I still had the "under pressure" bit in my mind, so I just went with what I knew:

    Code JavaScript:
    function getFileExtension(i) {
      // i will be a string, but it may not have a file extension.
      // return the file extension (with no period) if it has one, otherwise false
     
      var regEx = /.*\.(.+)/;
      if (i.match(regEx, "")){
        return i.replace(regEx, "");
      } else {
        return false;
      }
    }

    Which can be tidied up a bit:

    Code JavaScript:
    function getFileExtension(i) {
      var match = /.*\.(.+)/.exec(i)
      return (match)? match[1] : false;
    }

    Number four looked like this:

    Code JavaScript:
    function longestString(i) {
      // i will be an array.
      // return the longest string in the array
     
      var j,
          len = i.length,
          longest = "";
     
      for(j = 0; j < len; j++){
        if(typeof i[j] === "string"){
          if(i[j].length > longest.length){
            longest = i[j]
          }
        }
      }
    }

    However, last week Paul linked to a useful article abut filtering arrays, so I also tried to employ that:

    Code JavaScript:
    function longestString(i) {
      return i.filter(function (el) {
        return (typeof el === "string");
      }).sort(function(a, b){
        return b.length - a.length; 
      })[0];   
    }

    Which basically uses Array#filter to get all of the sting elements into an array, sorts the new array and returns the first element.

    With number five, like you, I started with a global variable, but that nagged at me, so I ended up with this:

    Code JavaScript:
    function arraySum(i) {
      // i will be an array, containing integers, strings and/or arrays like itself.
      // Sum all the integers you find, anywhere in the nest of arrays.
     
      var sum = 0,
          j, 
          len = i.length;
     
      for (j = 0; j < len; j++){
        if (i[j] instanceof Array) {
          sum += arraySum(i[j]);
        }
     
        if (typeof i[j] === "number"){ 
          sum += i[j];
        }
      } 
      return sum;
    }

    What got me here is that I was expecting to be able to test for an array with typeof i[j] === "array" which didn't work.

  13. #13
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    @Pullo ;

    Happy to see you've switched from equality == to identity === in your latest examples. We could be comparing to "0" using equality in @Paul O'B ; #2, for example, and due to type conversion, it will still work, but it's not advisable.

    A suggestion for #3:
    Code:
    function getFileExtension(i) {
        
        // i will be a string, but it may not have a file extension.
        // return the file extension (with no period) if it has one, otherwise false
        var extension = i.split(".").pop();
        return ( extension !== i ) ? extension : false;
        
    }
    Here I'm caching the result of string splitting, and get the last element, using Array.prototype.pop(). If the last (and only) element is the string itself, there was no splitting involved, so we return false.

  14. #14
    The CSS Clinic is open silver trophybronze trophy
    Paul O'B's Avatar
    Join Date
    Jan 2003
    Location
    Hampshire UK
    Posts
    40,549
    Mentioned
    183 Post(s)
    Tagged
    6 Thread(s)
    Quote Originally Posted by myty View Post
    @Pullo ;
    We could be comparing to "0" using equality in @Paul O'B ; #2, for example, and due to type conversion, it will still work, but it's not advisable.
    Ok thanks

    From reading a little it seems that its safer to always use "===" rather than "==".

  15. #15
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    You got it! MDN is the best JS resource for me: https://developer.mozilla.org/en-US/...ison_Operators

    For #4 and #5 actually functional programming design patterns is what comes to mind.

    #4
    @Pullo ; uses Array filter, one of the new additions to ecmascript. Unfortunately, it's not quite mainstream, but the underscore.js library is a good use here.

    We first reject from the array the non-string elements (first filter), and then max the longest string out (second filter): http://jsbin.com/OkOGIxI/2/edit
    Hide HTML and Output, show Console and hit run.


    #5
    Very similar to #4, except we flatten the array first, reject non-numbers this time, and reduce it to sum: http://jsbin.com/OkOGIxI/4/edit


    Functional programming design patterns bring clarity, and once the new Array methods become mainstream (once IE8 goes extinct), we can drop underscore.js. Until then, I'm glad this little gem of a library exists.

  16. #16
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    What got me here is that I was expecting to be able to test for an array with typeof i[j] === "array" which didn't work.
    Classic. Array is Object. Use toString in Object's prototype:
    Code:
    Object.prototype.toString.call( i[j] ).toString() === '[object Array]'

  17. #17
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,446
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Or:

    Code JavaScript:
    if ( Array.isArray(i[j] ) {

    Doesn't work on IE < 9, but it passes the test.

  18. #18
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi @myty ;

    Thanks for all the tips!
    I really like your solution for number 5 and will be looking more closely at underscore.js from now on.

  19. #19
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    You're welcome @Pullo ;.

    And it's a toss out with underscore.js. You can also check out lodash.js and lazy.js

  20. #20
    Just Blow It bronze trophy
    DaveMaxwell's Avatar
    Join Date
    Nov 1999
    Location
    Mechanicsburg, PA
    Posts
    7,290
    Mentioned
    122 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    I ended up having syntax issues when using typeof and blanked on instanceof, so a different solution was used by me.
    Now that I know that they do work, I'll take another run at things later.
    Those were what caused me fits as well, plus the fact that the values passed on a recursive array must be byRef instead of byVal in javascript.....

    Took me 12 minutes total, which included time stopped to discuss work issues, some language differences (C# vs javascript), plus a couple boneheaded problems on my part....
    Dave Maxwell - Manage Your Site Team Leader
    My favorite YouTube Video! | Star Wars, Dr Suess Style
    Learn how to be ready for The Forums' Move to Discourse

  21. #21
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DaveMaxwell View Post
    plus the fact that the values passed on a recursive array must be byRef instead of byVal in javascript.....
    This one reads odd to me. First, an array is not recursive by itself.

    I'm not so sure what you mean by values passed byRef: primitive values inside the array or the array itself. All I know is that in Javascript anything other than primitive values is passed by reference.

    Then, you probably heard that (almost) everything is an object in Javascript. Arrays in Javascript are high-level, list-like objects (Array - Javascript | MDN). To pass an array by value you can [].slice() it, although non-primitive values in it will still be passed by reference in the new array.

    Array.prototype.slice - Javascript | MDN
    slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array. Elements of the original array are copied into the new array as follows:

    For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

    For strings and numbers (not String and Number objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.

    If a new element is added to either array, the other array is not affected.

  22. #22
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,330
    Mentioned
    463 Post(s)
    Tagged
    8 Thread(s)
    I stumbled on an interesting article today that uses reduce() to solve question #4. It specifically references this quiz.

    Code JavaScript:
    function findLongest(entries) {
      return entries.reduce(function (longest, entry) {
        return entry.length > longest.length ? entry : longest;
      }, '');
    }

  23. #23
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ralph.m View Post
    I stumbled on an interesting article today that uses reduce() to solve question #4. It specifically references this quiz.
    }[/HIGHLIGHT]
    I just realize that I was going about it the wrong way and so is he and so the all of us. What if there is more than one longest string? The solution is a filter, not a max nor a fold (reduce).


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •