[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.javascript

Code Exercise, good for newbies!

dhtml

6/2/2014 11:44:00 PM

Write a function removeItem to remove a specified item from array.

function f(){}

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.
}




Using the following Array methods:

indexOf(o) -- added in ES5 (EcmaScript 5)
splice(start, deleteCount, insertItems);

Where possible, test in Internet Explorer back to version 8. Use
developer tools to switch IE version in IE. If you don't know how, do
a web search: switch version of IE developer tools
1 Answer

Scott Sauyet

6/3/2014 8:28:00 PM

0

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