lab15: impl

This commit is contained in:
2026-04-16 16:22:58 -07:00
parent aec8289f11
commit f0c3ba65a8

View File

@@ -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;
}
});
}
@@ -83,4 +109,5 @@ try {
console.log("Exception correctly thrown.");
}
delete arr[-2];
console.log(arr);