Skip to curriculum
Jump to the editor

10.3. An array that accepts only strings

Medium
Topics
15–30 min

A list of tags, CSS class names or user names should only ever hold strings. One stray number pushed into it shows up much later as a crash in tag.toLowerCase(), far from the code that put it there. A Proxy lets the array itself refuse the bad value at the moment it is written, so the error points at the real culprit.

Write createStringArray(...items) in string-array.js. It returns a real array (wrapped in a Proxy) that accepts only strings as items. Any attempt to put a non-string at an index throws a TypeError, whichever way it is attempted.

Signature

JAVASCRIPT
function createStringArray(...items) // returns a guarded array
  • items: the first items. If one of them is not a string, createStringArray throws a TypeError.
  • Returns an array: Array.isArray is true for it, and every array method works on it.

Requirements

  1. The result holds the given strings in order. createStringArray() is an empty array. Array.isArray(result) is true.
  2. A non-string initial item makes createStringArray throw a TypeError.
  3. Writing a string to an index works as on any array, including past the end (length grows). The empty string is a string.
  4. Writing any other value to an index (number, undefined, null, boolean, object, array, new String("x"), symbol, bigint, function) throws a TypeError, and that value is not stored: the index keeps what it held before.
  5. The rule holds for every way of writing an item: list[i] = v, push, unshift, splice, fill, Object.assign and Object.defineProperty. A getter or setter defined at an index is rejected too, and so is a descriptor without a value (such as {}) that would create a new index. A descriptor without a value may change the flags of an existing item.
  6. Each item is checked when it is written, one write at a time. A method that writes several items stops at the first refused one, and the writes it made before that stay: starting from ["a"], push("b", 3) throws and leaves ["a", "b"].
  7. The error message names the index that was refused.
  8. Only array indexes are guarded: property names that are whole numbers from 0 to 2 ** 32 − 2 written the canonical way ("0", "15", not "01", "-1" or "1.5"). length, named properties such as label, other strings and symbol keys accept any value, as on a normal array.
  9. length can still be set: shorter removes items, longer adds holes.
  10. Reading methods work and return ordinary arrays: list.map((s) => s.length) returns [1, 2], not an error. sort and reverse work.

Examples

JAVASCRIPT
const tags = createStringArray("css", "html");
tags.push("js");     // 3
tags.push(42);       // TypeError: index 3 accepts only strings
tags.length;         // 3: the bad push changed nothing
tags[0] = "CSS";     // fine
tags[1] = null;      // TypeError
JAVASCRIPT
const names = createStringArray("ann");
names.splice(0, 0, 7);                          // TypeError
Object.defineProperty(names, "0", { value: 1 }); // TypeError
names.label = 5;                                // fine: not an index
names["-1"] = 0;                                // fine: "-1" is not an array index
names.map((name) => name.length);               // [3]
JAVASCRIPT
createStringArray("a", 2);  // TypeError
createStringArray();        // []

Environment

  • Plain JavaScript in a browser page; the tests call the global createStringArray from string-array.js.
  • Use a Proxy around a real array. The tests do not care which traps you use, only that every write is checked.
  • Array.isArray must stay true, so do not return a plain object or a class instance.

Hints

  1. Which single trap do a direct write, push, fill and Object.assign all go through? And which one does Object.defineProperty use?
  2. A property key reaches a trap as a string. How can you tell "15" (an index) from "15.5" or "015" (not one)?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…