ArrayList
by jessekinsman
HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css">
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react-dom.js"></script>
<div id='target'>no snapshots</div>
CSS
td {
color: white;
padding: 5px;
text-align: center;
}
table {
margin-bottom: 10px;
}
Babel + JSX
/*
ArrayList
We are going to approximate an implementation of ArrayList. In JavaScript terms, that means we are
going to implement an array using objects. You should not use arrays at all in this exercise, just
objects. Make a class (or constructor function; something you can call new on) called ArrayList.
ArrayList should have the following properties (in addition to whatever properties you create):
length - integer - How many elements in the array
push - function - accepts a value and adds to the end of the list
pop - function - removes the last value in the list and returns it
get - function - accepts an index and returns the value at that position
delete - function - accepts an index, removes value from list, collapses,
and returns removed value
As always, you can change describe to xdescribe to prevent the unit tests from running while
you work
*/
class ArrayList {
constructor() {
this.length = 0;
this.data = {};
}
push(value) {
this.data[this.length] = value;
this.length++;
}
pop() {
const tmp = this.data[this.length-1];
delete this.data[this.length];
this.length--;
return tmp;
}
get(index) {
if (index > this.length) {
return undefined;
}
return this.data[index];
}
delete(index) {
const ans = this.data[index];
this._collapseTo(index);
return ans;
}
_collapseTo(index) {
if (index <= this.length) {
for (let i = index; i< this.length-1; i++) {
this.data[i] = this.data[i+1];
}
delete this.data[this.length];
this.length--;
}
}
}
// unit tests
// do not modify the below code
describe('ArrayList', function() {
const range = length => Array.apply(null, {length: length}).map(Number.call, Number);
const abcRange = length => range(length).map( num => String.fromCharCode( 97 + num ) );
let list;
beforeEach( () => {
list = new ArrayList();
})
it('constructor', () => {
...