Introduction
- This assignment will be worth 4% of your final grade.
- You will be marked on the last version pushed to coursegit. Make sure you have pushed your assignment by 4:30PM on Thursday October 23.
- For a detailed marking scheme, see javascript-assignment.
Questions
For this assignment you will a write JavaScript class List
.
The empty list is represented by the object null
, and a simple use
of List
is as follows
test("object", (t) => {
let list = new List(42, null);
assert.strictEqual(list.first,42);
assert.strictEqual(list.rest,null);
});
For full marks your implementation should avoid unnecessary copying, and should not use JavaScript arrays internally.
Q0: first
and rest
properties
The first
and rest
properties should be getters as discussed in
Chapter 6 of Eloquent
Javascript.
In particular, the following tests should pass.
test("first and rest are immutable", (t)=> {
let list = new List(42, null);
list.first = 0;
assert.strictEqual(list.first,42);
list.rest = new List(43,null);
assert.strictEqual(list.rest,null);
});
Q1: length
property
Write an length
property that calculates the length (number of values) of
a List
object. In particular your code should pass the following tests.
test("length: one node",
(t)=>{
let list1 = new List("hello",null)
assert.strictEqual(list1.length,1);
});
test("length: two nodes",
(t)=>{
let list2 = new List ("hello", new List("world", null));
assert.strictEqual(list2.length,2);
});
test("length: big list",
(t)=>{
let list3 = null;
for (let i=0; i<100; i++){
list3= new List (i,list3);
}
assert.strictEqual(list3.length,100);
});
Q2: Iterator
Add appropriate methods and classes so that your List
is iterable.
In particular the following tests should pass.
test("iterator 1",
(t)=>{
let list2 = new List ("hello", new List("world", null));
result="";
for (let val of list2) {
result+=val;
}
assert.strictEqual(result,"helloworld");
});
test("iterator 2",
(t)=>{
let list3 = null;
for (let i=0; i<100; i++){
list3= new List (i,list3);
}
let result = 0;
for (let val of list3) {
result+=val;
}
assert.strictEqual(result, 4950);
});