Can multiple operations on a list be performed in a single line of code?
In the Java programing language the following is legal syntax, it will compile, and when the code is executed it will move the elements in the list as intended.
//Rotate the list items one place to the left.
SomeLinkedList.addLast(SomeLinkedList.removeFirst());
Or
//Rotate the list items one place to the right.
SomeLinkedList.addFirst(SomeLinkedList.removeLast());
Can the same be done in microStudio?
Interesting question.
I tried this:
list = [10,20,30,40,50,60,70,80]
print(list)
list.push(list.removeAt(0))
print(list)
list.insert(list.removeAt(list.lenght-1))
print(list)
Console output:
[10,20,30,40,50,60,70,80]
[20,30,40,50,60,70,80,10]
[0,20,30,40,50,60,70,80,10]
So the left shift worked. Just couldn't get the right shift to work as shown.
But I'm just a tinkerer, the experts here might know better :)
Live Long and Tinker
It works when I add it as a function to the List prototype ... ???
(P.S. you can replicate the other commands you used doing so)
List.removeLast = function()
this.removeAt(this.length-1)
end
list = [10,20,30,40,50,60,70,80]
print(list)
list.push(list.removeAt(0))
print(list)
list.insert(list.removeLast())
print(list)
Output:
[10,20,30,40,50,60,70,80]
[20,30,40,50,60,70,80,10]
[10,20,30,40,50,60,70,80]
Now we really need the experts to point out what I did wrong in the first one :)
Just couldn't get the right shift to work as shown.
@TinkerSmith it works if you fix the typo list.lenght
-> list.length
;-)
... was just testing you ...
COUGH COUGH COUGH
:D
Just a tangential observation, this is why I don't like implicit return values on dynamically typed languages:
List.removeLast = function()
this.removeAt(this.length-1)
end
If I didn't see (or didn't look closely at) the usage example below it, I would've never presumed that this function returns something.
Thanks everyone for the feedback, it's much appreciated.
I did have a look at the List methods before posting, But as I'm just finding my way around the IDE and the microScript language at the moment I wasn't sure if the 'rotations' were possible.
Now that we know it works I hope that folks will find it useful.