0

The Python idiom in the subject line

set('pdf ppt tif tiff jpg jpeg'.split())

illustrates a fairly compact way to create a set of strings.1 I'm looking for a similarly compact idiom to create a set in JavaScript. (NB: I am not interested in merely creating a list of strings.)

I understand that the standard approach to sets in JS is to use objects (keys are set elements, values immaterial), but I have not hit upon a comparably succinct way to create such a set in JS.

FWIW, the idiom I'm looking for is intended for a bookmarklet (hence the emphasis on succinctness).

Thanks!

1 For those unfamiliar with Python, the inner expression just evaluates to the list of strings obtained by splitting the invoking string object at the whitespace; this list is then the argument to the set constructor.

Edit: emphasized that I'm looking for a set (i.e. object), not a list of strings.

kjo
  • 33,683
  • 52
  • 148
  • 265

2 Answers2

5

JavaScript doesn't have a set type but you need a helper function to easily create it from a string (or from an Array).

Here's such a helper function which will allow you to call .set() on a string and get an object mapping the items from the string to some value (true if none is specified):

String.prototype.set = function(val) {
    var items = this.split(' '),
        len = items.length,
        obj = {},
        i;
    for(i = 0; i < len; i++) {
        obj[items[i]] = val === undefined ? true : val;
    }
    return obj;
};

Demo:

> 'pdf ppt tif tiff jpg jpeg'.set()
{ pdf: true,
  ppt: true,
  tif: true,
  tiff: true,
  jpg: true,
  jpeg: true }

Since you prefer something succinct, this might be a solution for you if you only need it for a single string:

var set = (function(s){ var obj = {}; for(var i = 0, elems = s.split(' '), l = elems.length; i < l; i++) obj[elems[i]] = 1; return obj; })('pdf ppt tif tiff jpg jpeg');

In that case I would consider simply using an object literal though... that's most likely the shortest solution unless you have a ton of elements.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

ECMAScript 5th Edition has Array.reduce:

'pdf ppt tif tiff jpg jpeg'.split(' ').reduce(function(d,v){
    return d[v] = true,d
}, {});

Object
jpeg: true
jpg: true
pdf: true
ppt: true
tif: true
tiff: true
__proto__: Object
Esailija
  • 138,174
  • 23
  • 272
  • 326