3

I have a file whose sole purpose is to provide an enormous collection of key/value pairs in an object. It looks something like this:

var myobj = {
   some_key: 'some value',
   another_key: 'another value',
   // thousands of other key/value pairs...
   some_key: 'accidental duplicate key with different value'
};

Now when I reference that file and reference the some_key I get the accidental duplicate value because JavaScript will store the last declared key.

I want to write a unit test that checks this object for accidental duplicate keys. Problem is that JavaScript has already stripped out the duplicates. How would I accomplish this checking through unit tests?

(One answer would be to manually parse the file using string parsing to find the duplicates. This is brittle and I'd want to stay away from this.)

Guy
  • 65,082
  • 97
  • 254
  • 325
  • 1
    And changing the source of the file is impossible? – Henrik Andersson Jun 30 '14 at 15:39
  • 2
    "use strict" - will throw an error if you have duplicate keys (I think, haven't tested) – soktinpk Jun 30 '14 at 15:40
  • 2
    The problem is with who's creating that file, you should fix that rather than patch it later – Ruan Mendes Jun 30 '14 at 15:40
  • @soktinpk: Yeah, it does! :-) – gen_Eric Jun 30 '14 at 15:41
  • @DhavalMarthak I don't think that's what the OP is asking about, the OP's structure is something like `{a: 1, a: 2}` – Ruan Mendes Jun 30 '14 at 15:43
  • Unique keys have been a defining feature of semantic content association arrays since the very beginnings of computer science. Imagine if JavaScript arrays permitted duplicate values for a particular index number! Just as arrays should have unique keys, so should non-array objects. Special syntax should be required only when duplicate keys are actually wanted, if even then. My opinions. – David Spector Jun 22 '20 at 16:53

1 Answers1

8

Add "use strict"; to the top of your file. Example usage:

(function() {
  "use strict";
  // Throws a syntax error
  var a = {
    b: 5,
    b: 6
  };
})();

Edit: This answer is no longer strictly up to date due to ES6 computed property values. If you want, you can write your object as a JSON object (if that's possible) and put it through http://www.jslint.com/, which will check for duplicate keys. See as well: "use strict"; now allows duplicated properties?

Community
  • 1
  • 1
soktinpk
  • 3,778
  • 2
  • 22
  • 33
  • This does not throw an error in Node.js 0.10.42. In what JavaScript environment is it confirmed to throw? – Mark Stosberg Apr 04 '16 at 16:16
  • 1
    @MarkStosberg Unfortunately this answer no longer up to date (http://stackoverflow.com/questions/29936845/use-strict-now-allows-duplicated-properties) due to ES6 supporting computed property values – soktinpk Apr 04 '16 at 16:39