diff --git a/lab15/smart-array.js b/lab15/smart-array.js index 03d6ab7..5af767e 100644 --- a/lab15/smart-array.js +++ b/lab15/smart-array.js @@ -18,24 +18,24 @@ function SmartArray(...args) { let end = parseInt(prop.replace(RANGE_PAT, "$2")) + 1; return target.slice(start, end); } else if (prop.match(FROM_END_PAT)) { - // - // ***YOUR CODE HERE*** - // // Return the element at the specified position, counting // back from target.length. So "-1" will refer to the last // element in the array. // // If the resulting index position is negative, // raise an exception. + let indexFromEnd = parseInt(prop.replace(FROM_END_PAT, "$1")); + let index = target.length - indexFromEnd; + if (index < 0) { + throw new Error("Index out of bounds"); + } + return Reflect.get(target, index); } else { // Do the usual array thing -- get the value at the specified index. return Reflect.get(...arguments); } }, set: function(target, prop, newVal) { - // - // ***YOUR CODE HERE*** - // // For smart arrays, we only allow updates to numerical fields. // Throw an exception for a 'prop' that is not a valid integer. // @@ -43,7 +43,33 @@ function SmartArray(...args) { // // If negative, update the position counting from the end of the array. // However, raise an exception if the resulting index is still negative. + if (!prop.match(NUM_PAT)) { + throw new Error("Invalid index for assignment"); + } + let index = parseInt(prop); + if (index < 0) { + index = target.length + index; + if (index < 0) { + throw new Error("Index out of bounds"); + } + } + Reflect.set(target, index, newVal); + return true; }, + deleteProperty: function(target, prop) { + if (!prop.match(NUM_PAT)) { + throw new Error("Invalid index for deletion"); + } + let index = parseInt(prop); + if (index < 0) { + index = target.length + index; + if (index < 0) { + throw new Error("Index out of bounds"); + } + } + target.splice(index, 1); + return true; + } }); } @@ -78,9 +104,10 @@ try { } try { - arr[3*"hello"] = 'hello'; + arr[3 * "hello"] = 'hello'; } catch (e) { console.log("Exception correctly thrown."); } +delete arr[-2]; console.log(arr);