Search code examples
javascriptjqueryjquery-pluginsdata-structuresguava

js library to support various data structures? (like guava in java)


Coming from Java I really like the flexibility afforded by the rich collection of data structures provided by Guava. Is there a "guava-like" library in js or jquery?

Note: I heard about closure and it seems a bit heavy - anything simpler? (or is closure really what I need?)

Note 2: by "rich collection of data structures" I mean sorted maps and sets, multimaps (duplicate keys allowed) and multisets (sets with multiple entries allowed - seems strange but actually very useful!), etc.


Solution

  • If by "the rich collection of data structures" for JS you meant utility for operating on JavaScript Arrays and Objects and JavaScript itself, then I'd recommend Underscore.js:

    Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support. (...) Underscore provides 60-odd functions that support both the usual functional suspects: map, select, invoke — as well as more specialized helpers: function binding, javascript templating, deep equality testing, and so on. It delegates to built-in functions, if present, so modern browsers will use the native implementations of forEach, map, reduce, filter, every, some and indexOf.

    It also has Set-like functions like union, intersection and difference, type-checking functions isXXX (isArray etc.), function goodies and more stuff you'd write yourself without such a library.

    Underscore has clean code, is well tested and quite popular these days, I use it on daily basis in JS projects.


    EDIT after question edit:

    I know Guava has multimaps, multiset etc. but they are all consequesnce of Java design and it's hard to write 1 to 1 implementation of these collections in JS. It's because Javascript has no:

    • static typing,
    • classes in Java sense, uses prototyping instead (see this answer),
    • interfaces (but has functions as first-class objects on the other hand),
    • easily defined object equality (var t1 = { test: 1 }, t2 = { test: 1 }; t1 === t2 is false)

    so it's hard to write general-use Set implementation, not mentioning Multiset or Multimap. There are for example some Set implementations like Closure's one or this one, but they are not perfect - first modifies elements inserted into Set (!), the second is not a mainstream, well-tested project (and personally I've never used it so can't say more).

    In Javascript you just do var multimap = { key: [ 1, 2, 3.0 ], key2: [ 4, 'test', { bla: null }, 1 ] } and because of language design you can't just do multimap.containsValue({ bla: null }). I mentioned underscore.js because it has 95% utility functions you'll ever with JS collections, that is Arrays and Objects. If you want more, just use Closure's structs, but the library itself it's quite big.