Splicing exercise

C

Csaba Gabor

I'd like to write a
function insertArray(a1, a2, pos) { ... }
which will splice the a2.length elements of array a2 into array a1
starting at index position pos, and return the resultant array.

What is a "shortest" javascript function to do this?
Assume that you don't have to worry about error checking,
and that pos is an integer such that 0 <= pos <= a1.length
Can it be (semi reasonably) done as a single return statement?

Csaba Gabor from Vienna
 
T

Thomas 'PointedEars' Lahn

Csaba said:
I'd like to write a
function insertArray(a1, a2, pos) { ... }
which will splice the a2.length elements of array a2 into array a1
starting at index position pos, and return the resultant array.

What is a "shortest" javascript function to do this?

Is this a trick question?


PointedEars
 
V

VK

I'd like to write a
function insertArray(a1, a2, pos) { ... }
which will splice the a2.length elements of array a2 into array a1
starting at index position pos, and return the resultant array.

What is a "shortest" javascript function to do this?
Assume that you don't have to worry about error checking,
and that pos is an integer such that 0 <= pos <= a1.length
Can it be (semi reasonably) done as a single return statement?

I would rather to propose to your students to write a List data type
emulator. It could be a very good exercise on slice and splice methods
- this is what you are giving them right now, right? The final code
with errors correction can be found at my "List data type"
http://groups.google.com/group/comp.lang.javascript/msg/19ac11e0164d8ab4

Your question is a minor case of that and the solution is:

a1 = [1,2,3];
a2 = [10,20,30];

insertArray(a1,a2,1);

window.alert(a1);

function insertArray(a1, a2, pos) {
a1.splice(pos, 0, a2);
}

there is no need to return anything as it needlessly complicates the
code. If one still needs to create a new array then
a1.splice(pos, 0, a2);
return a1.slice(0);
 
T

Thomas 'PointedEars' Lahn

VK said:
function insertArray(a1, a2, pos) {
a1.splice(pos, 0, a2);
}

there is no need to return anything as it needlessly complicates the
code.

Nonsense. Returning the return value of a1.splice(...), which would only
"complicate the code" by 7 characters, would make the function insertArray()
more flexible in use.


PointedEars
 
V

VK

Nonsense.  Returning the return value of a1.splice(...), which would only
"complicate the code" by 7 characters, would make the function insertArray()
more flexible in use.

Tommy, I feel like it's really time to you to go to bed and start
tomorrow with a fresh head.
For sweeter dreams please check the return value of array's splice
method.
 
C

Csaba Gabor

Is this a trick question?

It wasn't meant to be. However, insertArray should
produce an array of length a1.length + a2.length,
which does not happen with VK's example.
 
T

Thomas 'PointedEars' Lahn

Csaba said:
It wasn't meant to be. However, insertArray should
produce an array of length a1.length + a2.length,
which does not happen with VK's example.

True. So, what have *you* tried?


PointedEars
 
C

Csaba Gabor

I would rather to propose to your students to write a List data type
emulator. It could be a very good exercise on slice and splice methods
- this is what you are giving them right now, right? The final code

No, I am not teaching. I encountered this issue today on
a project I'm working on, and thought I'd share.
with errors correction can be found at my "List data type"
 http://groups.google.com/group/comp.lang.javascript/msg/19ac11e0164d8ab4

Your question is a minor case of that and the solution is:

a1 = [1,2,3];
a2 = [10,20,30];

insertArray(a1,a2,1);
window.alert(a1);

function insertArray(a1, a2, pos) {
 a1.splice(pos, 0, a2);
}

there is no need to return anything as it needlessly complicates the
code. If one still needs to create a new array then
 a1.splice(pos, 0, a2);
 return a1.slice(0);

VK, my requested insertArray is meant to "imitate" PHP's
http://php.net/array_splice in that the second array's
*elements* are to be spliced in, rather than the array
itself. Specifically, the array that insertArray returns
should have a1.length + a2.length elements, and not
1 + a1.length as with your example. If this is confusing,
replace your window.alert with window.alert(a1.join(" ** "))
and you'll see what I mean.
 
V

VK

It wasn't meant to be.  However, insertArray should
produce an array of length a1.length + a2.length,
which does not happen with VK's example.

Of course, because it adds a2 array object as one member, not all a2
elements separately. The rest of coding, especially to have it as a
single return statement, would require the "SqueeseCrypt" coding style
which I hate a lot. In my strong opinion 2,3,4... separate statements
are better than a single statement cryptic mess: even if it's "cool"
looking. It is especially bad on the initial learning stage because
besides other things it plants the false idea into students' heads
that "lesser lines == better program". All this IMHO and nevertheless:

function insertArray(a1, a2, pos) {
return (new Array(a1.splice(pos, 0, a2), a1)).slice(1);
}
 
T

Thomas 'PointedEars' Lahn

VK said:
Of course, because it adds a2 array object as one member, not all a2
elements separately.

Which is not even remotely what the OP asked for. You get an "F".
The rest of coding, especially to have it as a
single return statement, would require the "SqueeseCrypt" coding style
which I hate a lot. In my strong opinion

.... which is worthless as usual as it is evidently not based on logical
thinking but on made-up bedtime stories ...
2,3,4... separate statements
are better than a single statement cryptic mess: even if it's "cool"
looking.

Or more efficient to no foreseeable disadvantage?
It is especially bad on the initial learning stage because
besides other things it plants the false idea into students' heads
that "lesser lines == better program".

Nobody who has posted in this thread is teaching students. Got it?
All this IMHO and nevertheless:

function insertArray(a1, a2, pos) {
return (new Array(a1.splice(pos, 0, a2), a1)).slice(1);
}

That still creates an array consisting of four elements (instead of the
specified five) -- [1, [10, 20, 30], 2, 3] -- for the posted test case.

So much for testing before posting, and labelling untested code, Often
Wrong.


PointedEars
 
T

Thomas 'PointedEars' Lahn

VK said:
Of course, because it adds a2 array object as one member, not all a2
elements separately.

Which is not even remotely what the OP asked for. You get an "F".
The rest of coding, especially to have it as a
single return statement, would require the "SqueeseCrypt" coding style
which I hate a lot. In my strong opinion

.... which is worthless as usual as it is evidently not based on logical
thinking but on made-up bedtime stories ...
2,3,4... separate statements
are better than a single statement cryptic mess: even if it's "cool"
looking.

Or more efficient to no foreseeable disadvantage?
It is especially bad on the initial learning stage because
besides other things it plants the false idea into students' heads
that "lesser lines == better program".

Nobody who has posted in this thread is teaching students. Got it?
All this IMHO and nevertheless:

function insertArray(a1, a2, pos) {
return (new Array(a1.splice(pos, 0, a2), a1)).slice(1);
}

That still creates an array consisting of four elements (instead of the
specified six) -- [1, [10, 20, 30], 2, 3] -- for the posted test case.

So much for testing before posting, and labelling untested code, Often
Wrong.


PointedEars
 
V

VK

So much for testing before posting, and labelling untested code, Often
Wrong.

Yes, yes, our Always Right one :) If you really got an insomnia (I am
fine with my rather early evening) you might try the previous task
with \00100-\uFFFD case insensitive pattern.

To OP:
As I said earlier I hate SqueeseCrypt'ing and respectively hate the
very look of it below instead of nicely followed separate
statements :), but if it would be a do-or-die task to have a single
return statement then:

a1 = [0,1,2];
a2 = ['a','b','c'];
a3 = insertArray(a1,a2,1);
window.alert(a3.length);
window.alert(a3);

function insertArray(a1, a2, pos) {
return [a1.splice(pos,0,a2),a1].pop().toString().split(',');
}
 
T

Thomas 'PointedEars' Lahn

VK said:
Yes, yes, our Always Right one :) If you really got an insomnia (I am
fine with my rather early evening)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
As your replying at 03:30 (your local time, 01:30 my local time) clearly
indicates ...

(You're such a *lousy* liar.)
you might try the previous task
with \00100-\uFFFD case insensitive pattern.

Whatever that is supposed to mean.
To OP:
As I said earlier I hate SqueeseCrypt'ing and respectively hate the
very look of it below instead of nicely followed separate
statements :), but if it would be a do-or-die task to have a single
return statement then:

a1 = [0,1,2];
a2 = ['a','b','c'];
a3 = insertArray(a1,a2,1);
window.alert(a3.length);
window.alert(a3);

function insertArray(a1, a2, pos) {
return [a1.splice(pos,0,a2),a1].pop().toString().split(',');
}

This works only for primitive values, if that. When will you ever learn?

A reasonable person would have checked *all* the methods of
`Array.prototype' before resorting to nonsense as above:

<https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/prototype>


PointedEars
 
T

Thomas 'PointedEars' Lahn

Johannes said:
Csaba Gabor :


Perhaps this ?

function insertArray(a1, a2, pos) {
return a1.slice(0, pos).concat(a2, a1.slice(pos, a1.length));
}

Exactly. You can omit the `a1.length' argument, though.

Now that the proverbial cat is out of the bag: there is an example very
similar to the test case posted by VK at
<https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/concat>

Had the OP read the Reference (included in "RTFM") as (I) recommended, and
referred to by the FAQ, instead of waiting for someone to post the spoon-fed
answer, they would have had the answer several hours earlier.

<http://jibbering.com/faq/#posting>


PointedEars
 
C

Csaba Gabor

Exactly.  You can omit the `a1.length' argument, though.

Looks good Johannes. Thanks for directly addressing the question.
Now that the proverbial cat is out of the bag: there is an
example very > similar to the test case posted by VK at
<https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global...>

Had the OP read the Reference (included in "RTFM") as (I) recommended,
and referred to by the FAQ, instead of waiting for someone to post the
spoon-fed answer, they would have had the answer several hours earlier.

Another botched presumption about me. It would be so refreshing
to see posts from you that are insult free, address issues head on,
and
are free of presumption about me. I was pleased to read your answer
and
had thought you'd turned over a new leaf at:
http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/5cfe80871d53b921/
since you had a specific solution to an asked question. I rather hope
it will become less of an anomaly.

But excuse me - Recommended? In your first 6(!) posts to this topic,
not one of which indicated that you had a competitive answer, the
only time I see a mention of reading a reference is in the 6th one.

But even had you referenced a manual in a halfway timely fashion,
without detracting from your message by encasing it in insult, it
would
not have been effective, because this phrase has in general become
almost a
joke as far as being helpful. In some cases, it's more of an
indication
that the person doesn't know the answer. It's about as useful as
saying,
"Read the relevant material, and you'll find an answer", or "Search on
google, someone's sure to have covered this in the past". Possibly
true, just not usually particularly helpful.

If a person wants to be helpful along these lines, then I
would suggest that it's far more effective to say, use these
search terms on Google: xxx yyy or If you look at the
following site it should address your question.

In any case, the OP (that would be me), already had an answer several
hours before posting. I did not post the question for my benefit; it
was rather meant as an excercise with an interesting point.

Johannes gave a nice answer. In my routine, where I do not need
to have a return value (yes, I realize it alters the problem)
since I can reuse the input array, I used:

function insertArray(a1, a2, pos) {
a1.splice.apply(aImg, [pos, 0].concat(a2)); }

which approach, by the way, I don't see directly mentioned
in the manual page you referenced.
 
T

Thomas 'PointedEars' Lahn

Johannes said:
Thomas 'PointedEars' Lahn wrote:

There is a problem, though : the OP asks for a function "which
will splice the a2.length elements of array a2 INTO array a1", my
capitals. The proposed solution does not : a1 is left unchanged.

The shortest (except for whitespace) exact solution I have found is

function insertArray(a1, a2, pos) {
return a1.splice(0, a1.length,
a1.slice(0, pos).concat(a2, a1.slice(pos))), a1;
}

but I rather hope it can be improved.

I surely hope so, because it returns the value of `a1' unchanged :)

The supposed nesting error aside, the obvious solution is to keep it as it
is and update the documentation. Another one is to work with another object
reference:

function insertArray(o, a2, pos)
{
var a1 = o.a;
return o.a.splice(0, a1.length, ...);
}

insertArray({a: [...]}, [...], 42);
Well, *you* could have posted an answer if you knew one,

True, but see below.
you were obviously on-line

How can you possibly tell?
and reading the thread.

But I wouldn't be a good teacher (and we're all teachers here, right? ;-))
if I gave the student the spoon-fed answer, would I? Instead I gave them
something to chew on, in small pieces, but they wouldn't even want to bite.

Now that you have given them the spoon-fed answer, they are going to assume
it is always going to work that way. I think that is a Bad Thing in the
end.

Please leave in an attribution line for each quotation level.


PointedEars
 
T

Thomas 'PointedEars' Lahn

Csaba said:
Another botched presumption about me. It would be so refreshing
to see posts from you that are insult free, address issues head on,
and
are free of presumption about me.

If you think that my stating the fact that you have been too lazy here
is an insult to you, then maybe I have hit the problem at bull's eye.

If you want to avoid "botched presumptions" about you, tell us what you
tried and we can help you with that.

This is not a support forum. You are not entitled to anything, let alone
a straightforward answer no matter how stupid you act (_not_: are).

I have given you the reference to the FAQ already, where all this is
explained; here is a more direct explanation that is also linked there:

<http://www.catb.org/~esr/faqs/smart-questions.html>


PointedEars
 
A

Asen Bozhilov

I'd like to write a
function insertArray(a1, a2, pos) { ... }
which will splice the a2.length elements of array a2 into array a1
starting at index position pos, and return the resultant array.


function insertArray(a1, b1, pos)
{
Array.prototype.splice.apply(a1, [pos, 0].concat(b1));
return a1;
}

If you doesn't want change a1 array, initialize new array in local
execution context and returned reference to that `object'.

function insertArray(a1, b1, pos)
{
var res_arr = [].concat(a1);
Array.prototype.splice.apply(res_arr, [pos, 0].concat(b1));
return res_arr;
}
 
T

Thomas 'PointedEars' Lahn

Johannes said:
Thomas 'PointedEars' Lahn :

Not if the comma operator is evaluated left to right, as it should,

Yes, my mistake.
The supposed nesting error aside, the obvious solution is to keep
it as it is and update the documentation.

That means changing the problem instead of solving it. [...]

No, it is just a different solution:

a1 = insertArray(a1, ...);
[...]
Another one is to work with another
object reference:

function insertArray(o, a2, pos)
{
var a1 = o.a;
return o.a.splice(0, a1.length, ...);
}

insertArray({a: [...]}, [...], 42);

The OP's solution, whith a minor change to correct a typo and another
one (using the comma operator) to provide the desired return value,
is even better, in my opinion :

function insertArray(a1, a2, pos) {
return a1.splice.apply(a1, [pos, 0].concat(a2)), a1;
}

By which criterion is that better? It requires Function.prototype.apply()
(compatibility issue), a nested call (performance issue), and is less clear
(code reuse issue).
However, this newsgroup is about *discussion* of javascript, not
lecturing. [...]

Exactly. It is _not_ a support forum where you ask questions and are
entitled to an (straightforward, helpful) answer.
I do.

I realise that placing each attribution immediately before the first
occurrence of its quotation level imposes some effort on subsequent
posters, but it makes correct attribution much easier for the reader,
especially if the quotations nest deeply. And I believe the comfort
of the reader is more important than that of the poster.

In that case you would probably be interested to know that in my humble
opinion (and that of many others, including the creators of Usenet, and the
authors of the FAQ of this NG), in-between attribution lines in electronic
written discussions disturb the flow of reading. There is also no need to
repeat attribution lines or place them in-between once it has been made
clear which quotation level refers to the text of which person. And, may I
doubt that your quoting style is your Pan's default?

<http://pan.rebelbase.com/screenshots/posting.png>


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top