TypeScript-STL (Standard Template Library, migrated from C++)
Full Changelog: https://github.com/samchon/tstl/compare/v2.5.13...v3.0.0
Full Changelog: https://github.com/samchon/tstl/compare/v2.5.12...v2.5.13
Full Changelog: https://github.com/samchon/tstl/compare/v2.4.11...v2.5.12
Related Project: https://github.com/samchon/tstl/projects/5
Related Project: https://github.com/samchon/tstl/projects/4
<thread>
<algorithm>
TGrid
<numeric>
Module <numeric>
has newly implemented in the TSTL by this v2.0 update. special_math
features, who implemented in the v1.7 update, are also belonged to this <numeric>
module.
export interface IComputable<Param, Ret = Param>
{
plus(val: Param): Ret;
minus(val: Param): Ret;
negate(): Ret;
multiplies(val: Param): Ret;
divides(val: Param): Ret;
modules(val: Param): Ret;
}
Mathmatical functions are also implemented in the <numeric>
module. If you want to utilize the algorithm functions with your own computable class, then extends the IComputable
interface and override the methods. Those methods would be used by below operators.
gcm
lcd
iota
accumulate
inner_product
adjacent_difference
partial_sum
inclusive_scan
& transform_inclusive_scan
exclusive_scan
& transform_exclusive_scan
plus
& minus
multiplies
& negate
divides
& modules
<functional>
A global function get_uid
has published.
export function get_uid(obj: Object): number;
You can get UID
(unique identifier) of parameter Object
by the function. The get_uid
function has existed since the start of TSTL, however, it's the first time that the feature has published (exported
) for users.
d.ts.map
https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#new---declarationmap
Since TypeScript v2.9 update, emitting declaration map files has been possible. To follow the TypeScript policy, TSTL also starts emitting the d.ts.map
files.
Unlike old versions who had merged source files (TS) into only a single JS file, v2.0 update does not merge them. Since the v2.0 update, output JS files are correspondent with each TS source file and they're connected by the the import
statement who follows the modular system (CommonJS
).
Thus, importing TSTL within browser level (<script src="tstl.js"></script>
) is not possible more. When you want to use the TSTL in browser application, then you must use a bundler like browserify
.
By the way, following the modular system, you can take an additional benefit. You can implement partial import by writing detailed path of the target feature like below:
// GLOBAL IMPORT
import * as std from "tstl";
// PARTIAL IMPORT IS ALSO POSSIBLE
import { Vector, TreeMap } from "tstl/container";
import a = require("tstl/iterator");
import b = require("tstl/algorithm");
import c = require("tstl/exception");
import d = require("tstl/functional");
import e = require("tstl/utility");
import sMath = require("tstl/numeric/special_math");
import { sleep_until, shared_timed_mutex } from "tstl/thread";
// SPECIAL FEATURES
import experimental = require("tstl/experimental");
import base = require("tstl/base");
https://github.com/samchon/tstl/blob/master/src/functional/comparators.ts
Global comparators in TSTL (used in associative containers), they've changed to compare origin type of parameters using the valueOf()
function since v2.0 update. Also, getting new type Bigint
is also possible.
less
equal_to
not_equal_to
, less_equal
, greater
, greater_equal
hash
Also, the comparable interface IComparable
has changed its methods to be required (optional symbol ?
is removed). If you need only partial feature of the IComparable
, then utilize the Pick
type.
interface IComparable<T>
{
equals(obj: T): boolean;
less(obj: T): boolean;
hashCode(): number;
}
declare class Point2D implements Pick<IComparable<MyClass>, "equals"|"less">
{
public x: number;
public y: number;
public equals(p: Point2D): boolean;
public less(p: Point2D): boolean;
}
export abstract class MapContainer<Key, T,
Unique extends boolean,
Source extends MapContainer<Key, T, Unique, Source>>
extends Container<Entry<Key, T>,
Source,
MapIterator<Key, T, Unique, Source>,
MapReverseIterator<Key, T, Unique, Source>>
{
public abstract insert(pair: IPair<Key, T>): MapContainer.InsertRet<Key, T, Unique, Source>;
public abstract emplace(key: T, val: T): MapContainer.InsertRet<Key, T, Unique, Source>;
}
export namespace MapContainer
{
export type InsertRet<Key, T,
Unique extends boolean,
Source extends MapContainer<Key, T, Unique, Source>>
= Unique extends true
? Pair<MapIterator<Key, T, Unique, Source>, boolean>
: MapIterator<Key, T, Unique, Source>;
}
Since v2.0 update, new generic parameter Unique
has newly added in the base SetContainer
and MapContainer
. Those base containers also have new abstract methods insert
and emplace
had not existed in the earlier versions.
The Unique
parameter would be specified in their sub-class level like UniqueMap
(TreeMap
and HashMap
) or MultiSet
(TreeMultiSet
and HashMultiSet
). Those specifications determine the return types of insert
and emplace
methods, using the conditional type
, new feature of TS v2.9
.
copy_backward
in <algorithm>
has been fixed.empty
in <iterator>
, returning opposite result, has been fixedExtension of TSTL Containers dispatching Events.
With TSTL v1.7 update, I've published a supplementary extension module which is named ECOL, too. ECOL is an extension module of this TSTL, providing special collections dispatching events. The special collections are almost similar with the original STL Containers, but you also can observe elements' I/O events with the special collections.
Types of the event dispatched by the special collections are "insert"
, "erase"
and "refresh"
.
import {TreeMapCollection} from "ecol";
function listener(event: TreeMapCollection.Event<number, string>): void
{
console.log("Event type is: " + event.type);
for (let it = event.first; !it.equals(event.last); it = it.next())
console.log("\t", "An element by that event:", it.value);
}
function main(): void
{
// CONSTRUCT EVENT TREE-MAP
let map: TreeMapCollection<number, string> = new TreeMapCollection();
map.addEventListener("insert", listener);
map.addEventListener("erase", listener);
// DISPATCHES INSERT EVENT
map.set(1, "One");
map.set(2, "Two");
map.set(3, "Three");
// DISPATCHES ERASE EVENT
map.erase(2);
map.erase(3);
// DISPATCHES REFRESH EVENT
map.set(2, "Second"); // DUPLICATED -> UPDATE
map.refresh(); // BY USER
}
main();
The Mathematical Special Functions have adopted in STL, since C++17 revise. Following the STL revise, TSTL also adapts the Mathematical Special Functions since v1.7 update.
List of Mathematical Special Functions are such below:
Insert Iterators are special output iterators, who have value setter (writeonly
). They're very suitable for global functions in <algorith>
module, espcialy whose name is ended as _copy
postfix.
Class Name | Global Factory Method | Required Method |
---|---|---|
InsertIterator |
inserter(Container) |
Container.insert(Iterator, Value) |
FrontInsertInserter |
front_inserter(Container) |
Container.push_front(Value) |
BackInsertIterator |
back_inserter(Container) |
Container.push_back(Vaue) |
The Insert Iteratores are type of forward iterators providing next()
method, however notice that, their next()
methods return only themseles (this
). They're adaptor classes calling insertion methods of their source containers repeatedly.
import std = require("tstl");
function main(): void
{
// 100, 99, 98, ..., 1
let list: std.List<number> = new std.List();
for (let i: number = 1; i <= 100; ++i)
list.push_front(i);
// INSERT ELEMENTS BY BACK_INSERTER
let vec: std.Vector<number> = new std.Vector();
std.copy(list.begin(), list.end(), std.back_inserter(vec));
// ELEMENTS IN `list` & `vec` ARE EQUAL.
console.log(std.equal(vec.rbegin(), vec.rend(), list.begin()));
}
main();
std.sample
& std.randint
Two global functions are newly added on the <algorithm>
module since C++17 revise.
The sample
is a sampling function picks up random n elements between [first, last) for inserts them to output. The picked up values (count: n) who would be inserted to the output iterator, they'll keep the origin sequence of [first, last).
The randint
is a function returns a random integer value between x and y. If x and y are integer, then the returned value can be one of them: x or y. Remember that, x must be less than y.
namespace std
{
export function sample<T,
InputIterator extends Readonly<IForwardIterator<T, InputIterator>>,
OutputIterator extends Writeonly<IForwardItertor<T, OutputIterator>>>
(
first: InputIterator, last: InputIterator,
output: OutputIterator, n: number
): OutputIterator;
export function randint(x: number, y: number): number;
}
<algorithm>
New global functions handling the heap
have newly added.
toJSON
method on ContainersSince v1.7 update, all containers in TSTL have toJSON()
method for JSON.stringify()
. By the method, you can serialize container to JSON-string, as a form of Array
storing its elements.
import std = require("tstl");
function main(): void
{
//----
// CONTAINER -> JSON
//----
let list: std.List<number> = new std.List();
for (let i: number = 0; i < 10; ++i)
list.push_back(i);
let str: string = JSON.stringify(list);
console.log(str); // "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
//----
// JSON -> CONTAINER
//----
let array: Array<number> = JSON.parse(str);
let deq: std.Deque<number> = new std.Deque(...array);
// ELEMENTS IN `list` & `deq` ARE SAME
console.log(std.equal(list.begin(), list.end(), deq.begin()));
}
main();
<algorithm>
& <iterator>
to be much more genericSince v1.7 update, global functions in <algorithm>
and <iterator>
have been much more generic.
Until the v1.6, global functions in the <algorithm>
and <iterator>
modules had forced that parameters of output-iterators and general-iterators to extend an abstract class [base.Iterator
], which occurs critical dependency. It was possible to utilizing built-in iterators, however, user-made customer iterators were not.
Since v1.7 update, all iterator parameters of global functions in the <algorithm>
and <iterator>
modules, they require objects to extend not a class, but an interface
. From now on, you can utilize your own-made iterators.
namespace std
{
export function copy<T,
InputIterator extends Readonly<IForwardIterator<T, InputIterator>>,
OutputIterator extends Writeonly<IForwardIterator<T, OutputIterator>>>
(
first: InputIterator, last: InputIterator,
output: OutputIterator
): OutputIterator;
}
This is a background story which is not important for users. This content is only for developers or participants of the TSTL project.
Until v1.6, abstract classes for containers and iterators were not enough strong within framework of type restriction and compilation. For example, abstract classes base.Container
and base.Iterator
, they've dependency relationships between themselves on their abstract methods. However, derived classes may override the abstract methods with derived types. Parameter and returned types are changed when overriding; it's danger, not safe for development.
Older Version
In contrary, since v1.7 update, it's not danger more. Developing the v1.7 update, I've learned a solution to avoid such danger by implementing Circular Dependency Relationships in Generics. By the solution, abstract classes of containers
and iterators
have been much stronger and proper in type checking.
Since v1.7 Update
Fixed errors in this v1.7 update, Most of them are caused by my misunderstandings about the STL features, defined by C++ standard committee. I'm sorry for these mistakes. Such mistakes are fixed since this v1.7 update and I promise to be careful for these mistakes.
PriorityQueue
When PriorityQueue.top() and PriorityQueue.pop() are called, then the largest value (when custom comparison function is specified, then the last value) must be returned and popped. However, old version of TSTL had returned and popped not the largest value, but the lowest value. Such critical problem has fixed since this v1.7 update.
Vector.pop_back()
Return type of Vector<T>.pop_back()
is deinfed to return void
, by the C++ standard committee. However, I'd done a mistake returning T
type (returned value is the last element that popped by the method) for a long time. Of course, it has fixed since this v1.7 update.
erase(Key)
methods in Multi Associative ContainersWhen erase(Key)
method, in associative containers allowing duplicated keys, is called, then all the matched key elements must be erased. However, I'd defined the method to erase only an element, the first one.
Such mis-features are fixed by this v1.7 update. From now on, the erase(Key)
method erases not only an element, but entire elements with the matched key and returns number of elements erased.
experimental
is correctA namespace storing experimental objects is experimental
. It's the standard and exact name. Naming the namespace as experiments, it was my mistake. I've recified my mistake since v1.7 update.
Objects allocated in the experimental
are such below:
The regular STL doesn't support utilizing reverse iterators in containers for directing position for inserting, updating or erasing elements. However, I'd misunderstood that it was possible. By the misunderstanding, I've developed TSTL to allow directing position by reverse iterators in containers are possible.
Since v1.7 update, such mistake has recified. Using reverse iterators in containers for directing position are impossible. Utilize the ReverseIterator.base()
method instead.
import std = require("tstl");
function main(): void
{
let list: std.List<number> = new std.List();
for (let i: number = 1; i <= 10; ++i)
list.push_back(i);
let r1: std.List.ReverseIterator<number> = list.rbegin();
let r2: std.List.ReverseIterator<number> = list.rend();
list.erase(r1, r2); // IMPOSSIBLE, BE ERROR SINCE V1.7
list.erase(r2.base(), r1.base()); // UTILIZE `base()` INSTEAD
}
main();
swap()
methods on List based ContainersWhen swap()
method is called in a List based Container, then its reverse iterators (rbegin()
, rend()
) were broken. This error is fixed in v1.7 update. List based containers mean:
Iterators of Set Containers, they'were miss-linked. Type definitions were correct, but reference links were all incorrect. It wasn't a critical problem as users of TSTL can't create Iterators of Set Containers by themselves. However, such error causes invalid invalid inspection using typeof
statement. This error has fixed in v1.7 update.
namespace std.TreeSet // (TreeSet, TreeMultiSet, HashSet, HashMultiSet)
{
// TYPE DEFINITIONS WERE CORRECT
export type Iterator<T> = std.base.SetIterator<T, TreeSet<T>>;
export type ReverseIterator<T> = std.base.SetReverseIterator<T, TreeSet<T>>;
// HOWEVER, LINKAGES WERE INCORRECT
export const Iterator = std.base.ArrayIterator;
export const ReverseIterator = std.base.ArrayReverseIterator;
}
ILockable.try_lock
has changed.To pursue consistency and avoid reversal calling between other promise typed methods, return type of the ILockable.try_lock() has changed from boolean
to Promise<boolean>
like ILockable.lock() and ILockable.unlock() who return Promise<void>
.
Function | Old Return Type | New Return Type |
---|---|---|
try_lock | number |
Promise<number> |
ILockable.try_lock | boolean |
Promise<boolean> |
SharedMutex.try_lock_shared | boolean |
Promise<boolean> |
random_shuffle
is removedGlobal function random_shuffle
is deprecated from C++14 and removed clearly since C++17 revise. To follow the standard, TSTL also removes the random_shuffle
function since v1.7 update. If you want the same feature, then utilize the shuffle
function.
tstl.min.js
In HTML, do not include tstl
by <script>
tag. Use bundler like browserify
instead. If you need a minified JS file, then utilize the bundler or minifier.