Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Functional programming, immutable collections and FP constructs for typescript and javascript

License

NotificationsYou must be signed in to change notification settings

emmanueltouzery/prelude-ts

Repository files navigation

NPM versionTestsapidoc

Intro

prelude-ts (previously prelude.ts) is a TypeScript library which aims to make functional programmingconcepts accessible and productive in TypeScript. Note that even though it'swritten in TypeScript, it's perfectly usable from JavaScript (including ES5)!

It providespersistentimmutable collections (Vector, Set, Map, Stream), and constructs such as Option,Either, Predicate and Future.

Vector.of(1,2,3).map(x=>x*2).head()// => Option.of(2)Option.sequence(Vector.of(Option.of(1),Option.of(2)))// => Option.of(Vector.of(1,2))Vector.of(1,2,3,4).groupBy(x=>x%2)// => HashMap.of([0, Vector.of(2,4)],[1, Vector.of(1,3)])Vector.of(1,2,3).zip("a","b","c").takeWhile(([k,v])=>k<3)// Vector.of([1,"a"],[2,"b"])HashMap.of(["a",1],["b",2]).get("a")// Option.of(1)

The collections are also JavaScript iterables, so if you have an ES6 runtime,you can use thefor .. of construct on them. If you're not familiar withimmutable collections,list.append(newItem) keepslist unchanged;append()returns a new list. Immutability helps reasoning about code.

You can check theUser Guide,and browse theAPI documentation,or ourblog.Note that the constructors are private, and you should use static methods to builditems — for instance:Option.of,Vector.of,Vector.ofIterable, and so on.

HashSet andHashMap are implemented using theHAMT algorithm,and concretely thehamt_plus library.Vector is implemented through abit-mapped vector trieand concretely thelist library, as of 0.7.7.In addition, the library is written in idiomatic JavaScript style, with loopsinstead of recursion, so the performance should be good(see benchmarks here comparing to immutable.js and more).list andhamt_plus are the two only dependencies of prelude-ts.

Set, Map and equality

JavaScript doesn't have structural equality, except for primitive types.So1 === 1 is true, but[1] === [1] is not, and neither is{a:1} === {a:1}.This poses problems for collections, because if you have aSet, you don'twant duplicate elements because of this limited definition of equality.

For that reason, prelude-ts encourages you to define for your non-primitive typesmethodsequals(other: any): boolean andhashCode(): number (the samemethods thatimmutable.js uses).With these methods, structural equality is achievable, and indeedVector.of(1,2,3).equals(Vector.of(1,2,3)) istrue. However this can onlywork if the values you put in collections have themselves properly defined equality(see how prelude-ts can help).If these values don't have structural equality, then we can get no better than=== behavior.

prelude-ts attempts to assist the programmer with this; it tries to encouragethe developer to do the right thing. It'll refuse types without obviously properlydefined equality in Sets and in Maps keys, soHashSet.of([1]),orVector.of([1]).equals(Vector.of([2])) will not compile.For both of these, you get (a longer version of) this message:

Type 'number[]' is not assignable to type 'HasEquals'.  Property 'equals' is missing in type 'number[]'.

See theUser Guidefor more details.

Installation

TypeScript must know aboutIterable, an ES6 feature (but present in most browsers)to compile prelude-ts. If you use TypeScript and target ES5, a minimum change to your tsconfig.jsoncould be to add:

"lib": ["DOM","ES5","ScriptHost","es2015.iterable"]

(compared to the default ES5 settings it only adds 'es2015.iterable')

Using in Node.js

Just add the dependency in yourpackage.json and start using it (likeimport { Vector } from "prelude-ts";, orconst { Vector } = require("prelude-ts");if you use commonjs).Everything should work, including type-checking if you use TypeScript. prelude-ts also providespretty-printing in the node REPL.

Using in the browser

Add the dependency in yourpackage.json; TypeScript should automaticallyregister the type definitions.

The npm package contains the filesdist/src/prelude_ts.js anddist/src/prelude_ts.min.js,which are UMD bundles; they work with other module systems and setprelude_tsas a window global if no module system is found. Include the relevant one in yourindex.html in script tags:

<scriptsrc="node_modules/prelude-ts/dist/src/prelude_ts.min.js"></script>

You shouldn't have an issue to import prelude-ts in your application, but if you usemodules it gets a little more complicated. One solution if you use them is to createanimports.d.ts file with the following contents:

// https://github.com/Microsoft/TypeScript/issues/3180#issuecomment-283007750import*as_Pfrom'prelude-ts';exportasnamespaceprelude_ts;export=_P;

Then in a.ts file of your application, outside of a module, you can do:

importVector=prelude_ts.Vector;

- to get values without the namespace.

Finally, if you also includedist/src/chrome_dev_tools_formatters.js throughascript tag, andenable Chrome custom formatters,then you can geta nice display of prelude-ts values in the Chrome debugger.

Wishlist/upcoming features

  • CharSeq, a string wrapper?
  • Non-empty vector? (already havenon-empty linkedlist)
  • Make use of trampolining or a similar technique inStream to avoid stack overflow exceptions on very large streams
  • More functions on existing classes

Out of scope for prelude-ts

  • Free monads
  • Monad transformers
  • Effect tracking
  • Higher-kinded types simulation

I think these concepts are not expressible in a good enough manner in a languagesuch as TypeScript.

Alternatives and Influences

  • monet.js -- only has theList andOption collections, implemented in functional-style ES5. The implementation,using recursion, means its list type is noticeably slower than prelude-ts's.
  • immutable.js -- doesn't have theOption concept; the types can be clunky.
  • sanctuaryoffers global functions likeS.filter(S.where(...)) while prelude-ts prefers afluent-API style likelist.filter(..).sortBy(...). Also, sanctuary doesn'toffer sets and maps. On the other hand, sanctuary has some JS runtime type systemsupport, which prelude-ts doesn't have.
  • ramdajs offers global functions likeR.filter(R.where(...)) while prelude-ts prefers afluent-API style likelist.filter(..).sortBy(...). Also, ramda doesn't offersets and maps. Ramda also uses currying a lot out of the box, which may notbe intuitive to a number of developers. In prelude,currying&partial applicationare opt-in.
  • lodash also has global functions, and many functionsmutate the collections.
  • vavr -- it's a Java library, but it's the main inspiration for prelude-ts.Note that vavr is inspired by the Scala library, so prelude-ts also is,transitively.

TypeScript version

As of 0.8.2, prelude requires TypeScript 3.1 or newer.

Commands

npm installnpm testnpm run-script docgennpm run benchmarks

Related projects

  • Prelude-IO, a library offering IO features -including deserializing and validation- on top of prelude-ts, emphasizing type-safety and immutability

About

Functional programming, immutable collections and FP constructs for typescript and javascript

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors11

Languages


[8]ページ先頭

©2009-2025 Movatter.jp