Giter Site home page Giter Site logo

typescript-collections's Introduction

It is a complete, fully tested data structure library written in TypeScript.

This project uses TypeScript Generics so you need TS 0.9 and above.

This projects supports UMD (Universal Module Definition)

NPM

Included data structures

  • Linked List
  • Dictionary - Example
  • Multi Dictionary
  • Linked Dictionary
  • Default Dictionary - Info
  • Binary Search Tree
  • Binary Search Tree for Key-Value pairs
  • Stack
  • Queue
  • Set - Example
  • Bag
  • Binary Heap
  • Priority Queue

It also includes several functions for manipulating arrays.

Usage

npm install typescript-collections --save

ES6 import ... from

import * as Collections from 'typescript-collections';

or TypeScript import ... require

import Collections = require('typescript-collections');

or JavaScript var ... require

var Collections = require('typescript-collections');

Visual Studio or other TypeScript IDE, will provide you with complete Intellisense (autocomplete) for your types. The compiler will ensure that the collections contain the correct elements.

A sample Visual Studio project is in the demo folder.

Also available on NuGet : http://www.nuget.org/packages/typescript.collections/ Thanks to https://github.com/georgiosd

Example

import * as Collections from 'typescript-collections';

var mySet = new Collections.Set<number>();
mySet.add(123);
mySet.add(123); // Duplicates not allowed in a set
// The following will give error due to wrong type:
// mySet.add("asdf"); // Can only add numbers since that is the type argument.

var myQueue = new Collections.Queue();
myQueue.enqueue(1);
myQueue.enqueue(2);

console.log(myQueue.dequeue()); // prints 1
console.log(myQueue.dequeue()); // prints 2

Typings resolution

Remember to set "moduleResolution": "node", so TypeScript compiler can resolve typings in the node_modules/typescript-collections directory.

In browser usage

You should include umd.js or umd.min.js from dist/lib/ directory.

<script src="[server public path]/typescript-collections/dist/lib/umd.min.js"></script>

A note on Equality

Equality is important for hashing (e.g. dictionary / sets). Javascript only allows strings to be keys for the base dictionary {}. This is why the implementation for these data structures uses the item's toString() method.

makeString utility function (aka. JSON.stringify)

A simple function is provided for you when you need a quick toString that uses all properties. E.g:

import * as Collections from 'typescript-collections';

class Car {
    constructor(public company: string, public type: string, public year: number) {
    }
    toString() {
        // Short hand. Adds each own property
        return Collections.util.makeString(this);
    }
}

console.log(new Car("BMW", "A", 2016).toString());

Output:

{company:BMW,type:A,year:2016}

A Sample on Dictionary

import * as Collections from 'typescript-collections';

class Person {
    constructor(public name: string, public yearOfBirth: number,public city?:string) {
    }
    toString() {
        return this.name + "-" + this.yearOfBirth; // City is not a part of the key.
    }
}

class Car {
    constructor(public company: string, public type: string, public year: number) {
    }
    toString() {
        // Short hand. Adds each own property
        return Collections.util.makeString(this);
    }
}
var dict = new Collections.Dictionary<Person, Car>();
dict.setValue(new Person("john", 1970,"melbourne"), new Car("honda", "city", 2002));
dict.setValue(new Person("gavin", 1984), new Car("ferrari", "F50", 2006));
console.log("Orig");
console.log(dict);

// Changes the same john, since city is not part of key
dict.setValue(new Person("john", 1970, "sydney"), new Car("honda", "accord", 2006));
// Add a new john
dict.setValue(new Person("john", 1971), new Car("nissan", "micra", 2010));
console.log("Updated");
console.log(dict);

// Showing getting / setting a single car:
console.log("Single Item");
var person = new Person("john", 1970);
console.log("-Person:");
console.log(person);

var car = dict.getValue(person);
console.log("-Car:");
console.log(car.toString());

Output:

Orig
{
    john-1970 : {company:honda,type:city,year:2002}
    gavin-1984 : {company:ferrari,type:F50,year:2006}
}
Updated
{
    john-1970 : {company:honda,type:accord,year:2006}
    gavin-1984 : {company:ferrari,type:F50,year:2006}
    john-1971 : {company:nissan,type:micra,year:2010}
}
Single Item
-Person:
john-1970
-Car:
{company:honda,type:accord,year:2006}

Default Dictionary

Also known as Factory Dictionary [ref.]

If a key doesn't exist, the Default Dictionary automatically creates it with setDefault(defaultValue).

Default Dictionary is a @michaelneu contribution which copies Python's defaultDict.

Development and contributions

Compile, test and check coverage npm run all

Supported platforms

  • Every desktop and mobile browser (including IE6)
  • Node.js
If it supports JavaScript, it probably supports this library.

Contact

bas AT basarat.com

Project is based on the excellent original javascript version called buckets

typescript-collections's People

Contributors

adhulipa avatar basarat avatar byxor avatar caselit avatar chriseppstein avatar cmandlbaur avatar cspotcode avatar episage avatar glegoux avatar hmil avatar jawilkins avatar jimeh87 avatar josephliccini avatar michaelneu avatar murat-mehmet avatar outlandnish avatar phiresky avatar sroucheray avatar vladad avatar xstoudi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typescript-collections's Issues

Identity Map?

I recently built an Identity Map data structure on top of the Dictionary data structure. It's like the Set in that keeps a single instance of an object for a given key, but it optimizes the use case of always using that single instance within other data structures so that mutations to it are always in sync, other javascript data structures like the default ES6 Set and Map objects also work much better when you can guarantee a single instance is in use. Also, this can cut down on memory usage by enabling GC on duplicative values.

https://gist.github.com/chriseppstein/11ae09e2d96f72af036645a481d879e3

Is there any interest in adding this here? If so, would love to get some feedback on the design before submitting a PR.

Use Heap properties to optimize .contains

I noticed you use pretty much .indexOf to get if an element is available within a heap.

Why don't you leverage the property of the heap's array representation to move from a O(N) to a O(lgN) complexity?

"Module not found"

Hi there,
I am using VS17 Enterprise.
I can easily import "typescript-collections" if I set my "module" option to "commonjs" in my tsconfig.json.
However, as soon as I change it to "umd" or "amd", I get error (see the screenshot please) saying that "Cannot find module 'typescript-collections'", and, therefore, the two variables "queue" and "queue1" will be of type "any". I have also attached my tsconfig.json.

Any help will be greatly appreciated.

main ts

tsconfig json

Cannot find name 'collections'

This project looks awesome! Unfortionally i couldn't get it to work.

I placed it in a directory 'vendor' and referenced it like described:
/// <reference path="vendor/typescript-collections/collections.ts" />

Which gives me the error: Cannot find name 'collections'. Also i tried to compile the demo (demo/CollectionsDemo/app.ts) which gives me the same error.

LinkedList remove all matching compare function

Hi,

It would be nice to include method in LinkedList removing all elements matching compare function.

Something like:

export interface IMatchFunction<T> {
	(a: T): boolean
}

removeAll(removeMatch: IMatchFunction<T>): number {

	//Remove all elements for which removeMatch returned true
	
	//Returns number of removed elements
	
}

This would allow removing elements without having full object handles.

Support for TypeScript 1.0

Doesn't work under Typescript 1.0; There are several compile-time issues; some are obvious to fix, however, there appears to be an issue with the DSTree where dequeue returns a Tand in one case a BSTreeNode is expected.

Firefox error "SyntaxError: missing = in const declaration"

When trying to use this library in Firefox I am getting the "SyntaxError: missing = in const declaration"

it appears that Firefox < version 51 has a bug in its implementation of "for(const" ....

Below is the Mozilla bug tracking this :
https://bugzilla.mozilla.org/show_bug.cgi?id=1101653

Just letting you all know that FF 52+ should resolve this ...

p.s. the bug was being hit when the util.ts -> makeString method was being called .. That has a for loop using a const

Reference equality by default

Hi. I added two separate functions to a set that were identical.

set.add(() => {})
set.add(() => {})

Because of the way toString() works, the set ended up containing only one function which is not expected. For reference the es6 Set class behaves in an expected way. It only checks for reference equality on objects.

This should be the default for Dictionary and Set in order to match es6 semantics.

Regards.

need @type package

do you have a related @type package of collections, the same thing as @types/bluebird-global does? for this kind basic datatype should not be "import" anywhere..

types not populating on objects instantiated from the data structures

I import the library using:

import * as Collections from "typescript-collections";

I then instantiate it:
var test = new Collections.Dictionary<string,number>();

but when I try to access properties using

test.propertyHere

The ide does not pick up the type. It shows no methods or properties for the object.

my tsconfig is as follows:

{
  "compilerOptions": {
    "module": "amd",
    "target": "es5",
    "sourceMap": true,
    "moduleResolution": "node"
  },
  "exclude": [
    "node_modules",
    "../typings"
  ]
}

I am using this in the browser with requirejs. It also does not seem to find the module with requirejs but I think that is another problem.

Support the Iterator protocol

I noticed most of these data structures don't support the ES6 iterator protocol:
*[Symbol.iterator](): IterableIterator<T>. Is the any interest in adding support for this protocol throughout the library so that these data structures can be used with for..of loops?

I implemented this for the identity map data structure (See issue #77) and it has been very useful.

Cannot find module 'typescript-collections' for versions >1.1.4.

Version 1.1.5, 1.1.6 and 1.1.7 cannot be loaded.

> const coll = require('typescript-collections')
Error: Cannot find module 'typescript-collections'
    at Function.Module._resolveFilename (module.js:455:15)
    at Function.Module._load (module.js:403:25)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at repl:1:14
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:96:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:313:29)
    at bound (domain.js:280:14)

node version 6.6.0, installed with npm 3.10.7

Using libary with Aurelia/Typescript

Hello,
I cant get this lib to fly with aurelia.
I registered the lib:

// aurelia.json
{
   "name": "typescript-collections",
   "path": "../node_modules/typescript-collections/dist",
   "main": "lib/umd.min"
}

And use an import :

// someServics.ts
import * as Collections from 'typescript-collections';

But I get an error: vendor-bundle.js:3763 Uncaught Error: Load timeout for modules: ....
Can anyone help please?

Allow LinkedDictionary setValue inserting to head

Currently setting value is adding to the list tail. Adding to the head is a frequent and useful operation (and if one needs it, there it is not possible to reuse anything in this implementation).

In general I think it was better not to hide completely the linked list structure from outside and allow in the linked dictionary an optional custom linked list appender.

Installation error

Error during installation:

[email protected] postinstall C:\Users\kshar\Documents\OneDrive\Scripts\Typescript\node_modules\typescript-collection

> typings install

'typings' is not recognized as an internal or external command,
operable program or batch file.
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] postinstall: `typings install`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\kshar\AppData\Roaming\npm-cache\_logs\2017-07-24T12_33_12_280Z-debug.log

Typings is deprecated and type definitions are now installed with npm i @types/abc. Perhaps an update is needed to post install script?

Split It Out Into Smaller Packages

Hi,
I was wondering if you considered splitting it out. If i only wanted to use X feature etc,
so that the overall size of the generated JS could be more fine grained.
Regards

Add .find() method

It'd be useful when you want to get a value not by it's key but any other attribute(s).
I currently extend the Dictionary class for this.

find(callback:(key:K, value:V) => any):V {
        let found:V;
        this.forEach((key:K, value:V) => {
            if (callback(key, value)) {
                found = value;
                return false; // break out
            }
            return undefined; // suppress "not all code paths return a value" error
        });
        return found;
 }

Note: .get() and .set() aliases (for .getValue and .setValue()) would be great too ๐Ÿค”

Great work btw!

Dictionary not working

Hi, looks like you dictionary isn't working:

var dict = new collections.Dictionary<{x:number},string>();   
console.log(dict.getValue({x:2}));   
dict.setValue({x:1}, 'x=1');   
console.log(dict.getValue({x:2}));   

I created a dictionary with a key: {x:number}

  1. Looking for the value for {x:2} returns undefined, which is correct.
  2. Then I setValue for key {x:1} to 'x=1'.
  3. Now, when I look for the value associated with key {x:2} I get 'x=1' - Incorrect, there should still be no value with key of {x:2}

Add license

Please add some license information. Thank you :-)

Error typescript-collections 404 (Not Found) with Angular 2 final

Hello I do have the following error after launching my project.

From an Angular 2 quick-start project, I just installed typescript-collecions:

GET http://localhost:63342/IMA%20Sentinel/node_modules/typescript-collections 404 (Not Found)
Error: Error: XHR error (404 Not Found) loading http://localhost:63342/IMA%20Sentinel/node_modules/typescript-collections
        at XMLHttpRequest.wrapFn [as _onreadystatechange] (http://localhost:63342/IMA%20Sentinel/node_modules/zone.js/dist/zone.js:636:29)
        at ZoneDelegate.invokeTask (http://localhost:63342/IMA%20Sentinel/node_modules/zone.js/dist/zone.js:225:37)
        at Zone.runTask (http://localhost:63342/IMA%20Sentinel/node_modules/zone.js/dist/zone.js:125:47)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:63342/IMA%20Sentinel/node_modules/zone.js/dist/zone.js:293:33)
    Error loading http://localhost:63342/IMA%20Sentinel/node_modules/typescript-collections as "typescript-collections" from http://localhost:63342/IMA%20Sentinel/app/history.service.js

Here is the history.service.ts file where I use a dictionary

import { Injectable } from '@angular/core';
import { Dto } from './dto';
import Collections = require('typescript-collections');

@Injectable()
export class HistoryService {

  public managedDtoDico : Collections.Dictionary<number, Dto> = new Collections.Dictionary<number, Dto>();

The package is installed here :
[projectName]\node_modules\typescript-collections

My tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }

}

Did I miss something ?

The NuGet package includes unnecessary files.

The NuGet package version 0.9.0 contains several files related to the building of the NuGet package but that should not be distributed.

Here is a list of the offenders:

  • NuGet.exe
  • build.ps1
  • publish.ps1
  • update.ps1

I believe this is because the nuspec file list is empty, so nuget is including every file/directory that is a sibling to the nuspec file. You should be able to resolve this by adding this block to the nuspec file under the package element (untested, details found at http://docs.nuget.org/create/nuspec-reference#specifying-files-to-include-in-the-package):

<files>
  <file src="content\*" target="content" />
</files>

Webpack build warning

Hello,

Thank you for the great lib. We are using it with a new angular 2 project and it works great. Only issue we have is a warning we get with Webpack at this point. It looks like your package.json points to umd.js instead of index.js.

Here is the error we get:
typescript-collections/dist/lib/umd.js
Critical dependencies:
21:121-128 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.

Thanks,
TK

Compilation error under TS v1.0.3.0

Hi!

I just have installed package and installed it for my project and have two errors in collection.ts file:

Type 'LinkedList<{}>' is not assignable to type 'LinkedList'. Type '{}' is not assignable to type 'T'.
and
Type '{}' is not assignable to type 'BSTreeNode'. Property 'element' is missing in type '{}'.

Apart that issues whole project is great :)

Thanks!
Aggie

Register on bower

Hi,
Would it be possible to register this library on bower?

Thanks

Compile error in latest version.

I just downloaded the latest Typescript, and tried the collection library, but there are some compile errors in collection.ts.

Cannot convert 'LinkedList<{}>' to 'LinkedList':

constructor() {
this.list = new LinkedList();
}

I think there may have been some changes in the latest TS that broke some lines.

In any case, I think the library is great - good work!

Greg

LICENSE.md deleted

It appears the license file was dropped. If you could, please publish a new maintenance version with a license file. (if still applicable?)

original issue: #14

offending commit: d000acf

building the library...

this library is fantastic ๐Ÿ˜„

i copied the structure for a project i'm working on.

i noticed that in the package.json, none of the commands run tsd install, but i had to do the following to get npm run all to work without errors:

npm install -g tsd
tsd install

Add support for a toKey symbol?

In ES6, the canonical use case for symbols is so that objects can implement special methods for use by other data structures. It seems like an ideal situation for this library to add support for a toKey method that could be used throughout this library. I implemented the concept in this data structure for identity map, but I think it could be generalized.

Unfortunately, there's not currently a way to create a typescript interface around a custom symbol. I suspect TS will add this soon enough, they've indicated they want to handle it on the issue tracker.

https://gist.github.com/chriseppstein/11ae09e2d96f72af036645a481d879e3

Compilation error on TS0.9.5.0

I found to issues when compiling on TS0.9.5.0:

collections.ts(1511,13): error TS2012: Cannot convert 'LinkedList<{}>' to 'LinkedList<T>': Types of property 'firstNode' of types 'LinkedList<{}>' and 'LinkedList<T>' are incompatible: Types of property 'element' of types 'ILinkedListNode<{}>' and 'ILinkedListNode<T>' are incompatible.
collections.ts(2410,17): error TS2012: Cannot convert '{}' to 'BSTreeNode<T>': Type '{}' is missing property 'element' from type 'BSTreeNode<T>'.

Making the following corrections seems to sort it out:

Line 1511 changed to "this.list = new LinkedList();"
Line 2405 changed to "var queue = new Queue<BSTreeNode>();"

Hope this comment helps others and that you get these or other corrections done in the code so it compiles. Let me know if I can be of any assistance.

1.2.4 breaks import

I'm unable to import typescript-collections as of version 1.2.4. Right now I'm manually locking the version to 1.2.3. Let me know what I can do to help debug.

To/From JSON Support

Hi
Please include to/from json support.
JSON.stringigy(dictionary ); // this should print only a map and not meta data
dic = JSON.parse(str); //JSON should cast to Dictionary collection and you can identify the collection since it should have defined type.

Publish on NPM?

This looks like it'd be interesting to use, have you considered publishing it on NPM?

Using library in Angular 2

Hi,

I've been ripping my hair out for hours. I think there is something that I don't seem to understand about how this whole packaging/modular stuff works in this Javascript world.

I've basically got an Angular 2 app which plays nicely with anything that has nice compatible modules already available. No matter what I try I can't get this to work. I'm also using Webpack.

I basically did the following:

npm install typescript-collections --save

I then did

typings install file:./node_modules/typescript-collections/collections.d.ts

This put the typings file in my typings folder in the "browser" and "main" folders etc and added this to my code:

/// <reference path="browser\definitions\collections\collections.d.ts" />

However, now I'm trying to do something like:

this._apps = new collections.Dictionary<string, AppModel>();

But I just simply get the error "ReferenceError: collections is not defined".

I tried:

import { collections } from 'typescript-collections/collections';

import 'collections';

import 'typescript-collections/collections';

require('typescript-collections');

require('../node_modules/typescript-collections/collections');

Still, I get the same error.

Interestingly in my Atom editor intellisense is working fine and it sees all these modules, however when running this in the browser I just get collections is not defined.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.