Before the lab
- Read about Optional arguments
- Read Chapter 4 of Eloquent JavaScript
labs/L09 inside your ~/cs2613 git repositoryJavaScript supports arrays. They are actually implemented as objects, which leads to some slightly surprising behaviour:
> x=[]
> x[10]=1
> x
> x["bob"] = 2
> x
Follow the (first part of the)
Sum of a Range Exercise
to write a range function that passes the following tests.
test("empty", (t)=>assert.deepStrictEqual(range(2,1),[]));
test("single", (t)=> assert.deepStrictEqual(range(2,2),[2]));
test("multiple", (t)=>
assert.deepStrictEqual(range(42,50),[42,43,44,45,46,47,48,49,50]));
Follow the (second part of the)
Sum of a Range Exercise
to write a sum function that passes the following tests.
test("empty", (t)=> assert.strictEqual(sum([]),0));
test("single", (t)=> assert.strictEqual(sum([2]),2));
test("multiple", (t)=> assert.strictEqual(sum(range(1,10)),55));
Add an optional step argument to the range function so that the following tests pass. The original tests should keep passsing, that's a big part of the point of having unit tests.
test("step 2", (t)=> assert.deepStrictEqual(range(1,10,2),[1,3,5,7,9]));
test("step -1", (t)=> assert.deepStrictEqual(range(5,2,-1),[5,4,3,2]));
Solve the Flatten
Exercise
using reduce and concat methods. Your solution should pass the
following test suite.
test("base case", ()=> assert.deepStrictEqual(flatten([]),[]))
test("single element",
function () {
assert.deepStrictEqual(flatten([1]),[1]);
assert.deepStrictEqual(flatten(["foo"]),["foo"]);
assert.deepStrictEqual(flatten([{foo: 1}]),[{foo: 1}]);
});
test("longer list", ()=>
assert.deepStrictEqual(flatten([[1],2,[3],4,[5,6]]),[1,2,3,4,5,6]));
Does the following test pass with your implementation? If not, why not?
test("deeper nesting", (t)=>
assert.deepStrictEqual(flatten([[[1],2,[3]],4,[5,6]]),[1,2,3,4,5,6]));
Here is a question for you to think about:
reduce more like Racket's foldl or foldr?Solve the Every Exercise
Call the version using a loop every_loop
test("all true", (t)=>
assert.strictEqual(every_loop([1, 3, 5], n => n < 10), true));
test("last false", (t)=>
assert.strictEqual(every_loop([2, 4, 16], n => n < 10), false));
test("last middle false", (t)=>
assert.strictEqual(every_loop([2, 16, 3], n => n < 10), false));
test("empty list", (t)=>
assert.strictEqual(every_loop([], n => n < 10),true));
Call the version using the some method every_some. The tricky part here
is to construct a function that is the negation of the given function.
test("all true", (t)=>
assert.strictEqual(every_some([1, 3, 5], n => n < 10), true));
test("last false", (t)=>
assert.strictEqual(every_some([2, 4, 16], n => n < 10), false));
test("last middle false", (t)=>
assert.strictEqual(every_some([2, 16, 3], n => n < 10), false));
test("empty list", (t)=>
assert.strictEqual(every_some([], n => n < 10),true));