Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #24592

Re: Code Exercise, good for newbies!

Newsgroups comp.lang.javascript
Date 2014-06-03 13:28 -0700
References <3206f477-4226-48fb-84d5-bfb012f0271a@googlegroups.com>
Message-ID <b0f8b457-2909-4cd3-9d39-7373e4e3c3ed@googlegroups.com> (permalink)
Subject Re: Code Exercise, good for newbies!
From Scott Sauyet <scott.sauyet@gmail.com>

Show all headers | View raw


dhtml wrote:
> Write a function removeItem to remove a specified item from array. 
> [ ... ]
> 
>     var a = [1, "bird", f];
>     var b = [2, "dog", null];
> 
>     removeItem(a, f); // expect a as [1, "bird"]
>     removeItem(b, "dog"); // expect b as [2, null]
> 
>     function removeItem(array, item) {
>       // Your code goes here.
>     } 
> [ ... ]

Three things:

First, you probably don't want the fact that this is an excercise 
aimed at newcomers to be only in your title.  It really should be
included in the text, IMHO.

Second, you don't really describe the behavior of the function. Does 
it mutate the arrays or returns copies without the offending item? 
Does it remove all copies of the offending item or only the first 
one? If it doesn't return the arrary or an updated copy, what does 
it return? 

Third, I would suggest that the order of the parameters should be 
reversed: 

    function removeItem(item, array) { /* ... */ }
    
This would allow the user to curry the function in a more useful 
manner, or, even better, have it automatically curried:

    var removeItem = curry(function(item, array) {/* ... */});

While this is perhaps beyond the expected level of the beginners
expected to solve the problem, early exposure to these techniques
could not hurt.  If they write APIs in a more useful manner, it
will make it easier for them to learn these skills later.
    
If the function were written like that, it could then be used thus:

    var removeDog = removeItem("dog");
    removeDog(b);  // OR
    allArrays.forEach(removeDog);
    
If it does return the array -- either the mutated orginal or an
updated copy -- then it could be used with simple functional
composition to build larger functions:

    var update = compose(reverse, removeDog, capitalize);
    update(["fish", "dog", "cat"]); //=> ["Cat", "Fish"]

(for appropriate definitions of `reverse` and `capitalize`, of 
course.)

There are times when one might want to curry the function in the 
order presented, but it seems much less likely, and those could 
be handled with a simple `flip` function. 

Obviously there can be real depth even in simple problems.

  -- Scott

Back to comp.lang.javascript | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Code Exercise, good for newbies! dhtml <dhtmlkitchen@gmail.com> - 2014-06-02 16:44 -0700
  Re: Code Exercise, good for newbies! Scott Sauyet <scott.sauyet@gmail.com> - 2014-06-03 13:28 -0700

csiph-web