From 0976c1923e7da6fee5a0a587a55f6af11efcc053 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Fri, 29 Mar 2024 02:08:08 +0900 Subject: [PATCH 1/2] Adjust prettier --- .prettierignore | 4 - .vscode/launch.json | 59 +- .vscode/settings.json | 10 + package.json | 3 +- prettier.config.js | 12 + rollup.config.js | 54 +- src/algorithm/binary_search.ts | 116 +- src/algorithm/heap.ts | 282 +- src/algorithm/iterations.ts | 730 ++-- src/algorithm/mathematics.ts | 308 +- src/algorithm/merge.ts | 360 +- src/algorithm/modifiers.ts | 873 +++-- src/algorithm/partition.ts | 172 +- src/algorithm/random.ts | 84 +- src/algorithm/sorting.ts | 257 +- src/base/container/Container.ts | 212 +- src/base/container/IArrayContainer.ts | 185 +- src/base/container/IContainer.ts | 324 +- src/base/container/IDequeContainer.ts | 135 +- src/base/container/IHashMap.ts | 136 +- src/base/container/IHashSet.ts | 123 +- src/base/container/ILinearContainer.ts | 290 +- src/base/container/ITreeMap.ts | 145 +- src/base/container/ITreeSet.ts | 91 +- src/base/container/MapContainer.ts | 656 ++-- src/base/container/MultiMap.ts | 205 +- src/base/container/MultiSet.ts | 154 +- src/base/container/SetContainer.ts | 499 ++- src/base/container/UniqueMap.ts | 516 ++- src/base/container/UniqueSet.ts | 277 +- src/base/index.ts | 1 + src/base/thread/ILockable.ts | 104 +- src/base/thread/ISharedLockable.ts | 209 +- src/base/thread/ISharedTimedLockable.ts | 173 +- src/base/thread/ITimedLockable.ts | 85 +- src/benchmark/exceptions.ts | 281 +- src/benchmark/index.ts | 97 +- src/benchmark/internal/TimeWatch.ts | 10 +- src/benchmark/ranges.ts | 60 +- src/benchmark/sorts.ts | 51 +- src/container/Deque.ts | 1244 ++++--- src/container/ForwardList.ts | 1107 +++--- src/container/HashMap.ts | 622 ++-- src/container/HashMultiMap.ts | 720 ++-- src/container/HashMultiSet.ts | 651 ++-- src/container/HashSet.ts | 590 ++-- src/container/List.ts | 804 +++-- src/container/PriorityQueue.ts | 247 +- src/container/Queue.ts | 79 +- src/container/Stack.ts | 63 +- src/container/TreeMap.ts | 307 +- src/container/TreeMultiMap.ts | 308 +- src/container/TreeMultiSet.ts | 295 +- src/container/TreeSet.ts | 291 +- src/container/Vector.ts | 204 +- src/container/VectorBoolean.ts | 757 ++--- src/exception/DomainError.ts | 17 +- src/exception/ErrorCategory.ts | 109 +- src/exception/ErrorCode.ts | 46 +- src/exception/ErrorCondition.ts | 30 +- src/exception/Exception.ts | 84 +- src/exception/InvalidArgument.ts | 17 +- src/exception/LengthError.ts | 17 +- src/exception/LogicError.ts | 17 +- src/exception/OutOfRange.ts | 17 +- src/exception/OverflowError.ts | 17 +- src/exception/RangeError.ts | 17 +- src/exception/RuntimeError.ts | 17 +- src/exception/SystemError.ts | 98 +- src/exception/UnderflowError.ts | 17 +- src/experimental/container/FlatMap.ts | 301 +- src/experimental/container/FlatMultiMap.ts | 301 +- src/experimental/container/FlatMultiSet.ts | 263 +- src/experimental/container/FlatSet.ts | 261 +- src/experimental/index.ts | 1 + src/functional/IComparable.ts | 40 +- src/functional/IPointer.ts | 18 +- src/functional/bit_operations.ts | 12 +- src/functional/comparators.ts | 50 +- src/functional/hash.ts | 107 +- src/functional/uid.ts | 33 +- src/index.ts | 1 + src/internal/Global.ts | 15 +- .../associative/IAssociativeContainer.ts | 237 +- .../container/associative/IHashContainer.ts | 383 ++- .../container/associative/ITreeContainer.ts | 369 +- .../container/associative/MapElementList.ts | 458 +-- .../container/associative/MapElementVector.ts | 394 ++- .../container/associative/MultiTreeMap.ts | 265 +- .../container/associative/MultiTreeSet.ts | 216 +- .../container/associative/SetElementList.ts | 342 +- .../container/associative/SetElementVector.ts | 270 +- .../container/associative/UniqueTreeMap.ts | 203 +- .../container/associative/UniqueTreeSet.ts | 163 +- .../container/linear/AdaptorContainer.ts | 79 +- .../container/linear/ArrayContainer.ts | 459 ++- .../container/linear/ILinearContainerBase.ts | 154 +- .../container/linear/IListAlgorithm.ts | 87 +- .../container/linear/ListContainer.ts | 566 ++-- .../container/linear/VectorContainer.ts | 346 +- src/internal/container/partial/IClear.ts | 8 +- src/internal/container/partial/IDeque.ts | 9 +- src/internal/container/partial/IEmpty.ts | 8 +- src/internal/container/partial/IFront.ts | 24 +- src/internal/container/partial/IInsert.ts | 7 +- src/internal/container/partial/IPush.ts | 14 +- src/internal/container/partial/IPushBack.ts | 20 +- src/internal/container/partial/IPushFront.ts | 12 +- src/internal/container/partial/ISize.ts | 8 +- src/internal/exception/ErrorGenerator.ts | 187 +- src/internal/exception/ErrorInstance.ts | 153 +- src/internal/hash/HashBuckets.ts | 199 +- src/internal/hash/MapHashBuckets.ts | 109 +- src/internal/hash/SetHashBuckets.ts | 102 +- src/internal/iterator/ArrayIterator.ts | 76 +- src/internal/iterator/ArrayIteratorBase.ts | 199 +- src/internal/iterator/ArrayReverseIterator.ts | 62 +- .../iterator/ArrayReverseIteratorBase.ts | 118 +- src/internal/iterator/InsertIteratorBase.ts | 38 +- src/internal/iterator/ListIterator.ts | 253 +- src/internal/iterator/ReverseIterator.ts | 121 +- .../iterator/disposable/ForOfAdaptor.ts | 75 +- .../disposable/NativeArrayIterator.ts | 81 +- src/internal/iterator/disposable/Repeater.ts | 45 +- src/internal/numeric/Carlson.ts | 91 +- src/internal/numeric/MathUtil.ts | 75 +- src/internal/thread/AccessType.ts | 4 +- src/internal/thread/LockType.ts | 4 +- src/internal/thread/SafeLock.ts | 62 +- src/internal/tree/Color.ts | 4 +- src/internal/tree/MapTree.ts | 225 +- src/internal/tree/MultiMapTree.ts | 187 +- src/internal/tree/MultiSetTree.ts | 178 +- src/internal/tree/SetTree.ts | 174 +- src/internal/tree/UniqueMapTree.ts | 107 +- src/internal/tree/UniqueSetTree.ts | 112 +- src/internal/tree/XTree.ts | 468 +-- src/internal/tree/XTreeNode.ts | 55 +- src/iterator/BackInsertIterator.ts | 77 +- src/iterator/FrontInsertIterator.ts | 68 +- src/iterator/IBidirectionalIterator.ts | 21 +- src/iterator/IForwardIterator.ts | 35 +- src/iterator/IRandomAccessIterator.ts | 35 +- src/iterator/IReversableIterator.ts | 20 +- src/iterator/IReverseIterator.ts | 20 +- src/iterator/InsertIterator.ts | 71 +- src/iterator/factory.ts | 87 +- src/iterator/global.ts | 129 +- src/module.ts | 1 + src/numeric/IComputable.ts | 11 +- src/numeric/INegatable.ts | 2 +- src/numeric/operations.ts | 426 +-- src/numeric/operators.ts | 65 +- src/numeric/special_math/bessels.ts | 146 +- src/numeric/special_math/beta.ts | 3 +- src/numeric/special_math/ellints.ts | 75 +- src/numeric/special_math/expint.ts | 53 +- src/numeric/special_math/gamma.ts | 22 +- src/numeric/special_math/hermite.ts | 33 +- src/numeric/special_math/laguerres.ts | 43 +- src/numeric/special_math/legendres.ts | 85 +- src/numeric/special_math/zeta.ts | 57 +- src/ranges/algorithm/binary_search.ts | 47 +- src/ranges/algorithm/heap.ts | 52 +- src/ranges/algorithm/iterations.ts | 327 +- src/ranges/algorithm/mathematics.ts | 81 +- src/ranges/algorithm/merge.ts | 224 +- src/ranges/algorithm/modifiers.ts | 370 +- src/ranges/algorithm/partition.ts | 79 +- src/ranges/algorithm/random.ts | 17 +- src/ranges/algorithm/sorting.ts | 81 +- .../container/IBidirectionalContainer.ts | 106 +- src/ranges/container/IForwardContainer.ts | 79 +- .../container/IRandomAccessContainer.ts | 47 +- src/ranges/index.ts | 1 + src/ranges/numeric/operations.ts | 230 +- src/test/algorithm/test_binary_searches.ts | 210 +- src/test/algorithm/test_heaps.ts | 68 +- src/test/algorithm/test_is_unique.ts | 14 +- src/test/algorithm/test_iterations.ts | 127 +- src/test/algorithm/test_mathmatics.ts | 42 +- src/test/algorithm/test_merges.ts | 131 +- src/test/algorithm/test_modifiers.ts | 53 +- src/test/algorithm/test_partitions.ts | 16 +- src/test/algorithm/test_randoms.ts | 50 +- src/test/algorithm/test_sortings.ts | 83 +- src/test/container/test_adaptors.ts | 98 +- src/test/container/test_associatives.ts | 637 ++-- src/test/container/test_for_of_iterations.ts | 104 +- src/test/container/test_hash_maps.ts | 64 +- src/test/container/test_linears.ts | 176 +- src/test/container/test_lists.ts | 172 +- src/test/container/test_swaps.ts | 331 +- src/test/container/test_trees.ts | 259 +- src/test/container/test_vector_bools.ts | 231 +- src/test/exception/test_names.ts | 30 +- src/test/functional/test_comparators.ts | 47 +- src/test/functional/test_hash.ts | 2 +- src/test/index.ts | 136 +- src/test/internal/ArrayUtil.ts | 24 +- src/test/internal/Atomic.ts | 26 +- src/test/internal/Cube.ts | 108 +- src/test/internal/Generator.ts | 93 +- src/test/internal/Point2D.ts | 60 +- src/test/iterator/test_inserters.ts | 22 +- src/test/manual/70.ts | 46 +- src/test/numeric/special_math/data.json | 3004 ++++++++--------- src/test/numeric/test_numeric_algorithms.ts | 161 +- src/test/numeric/test_special_maths.ts | 90 +- src/test/test_exports.ts | 113 +- src/test/thread/test_condition_variables.ts | 106 +- src/test/thread/test_mutable_singleton.ts | 52 +- src/test/thread/test_mutexes.ts | 423 ++- src/test/thread/test_safe_locks.ts | 146 +- src/test/thread/test_semaphores.ts | 169 +- src/test/thread/test_shared_mutexes.ts | 111 +- src/test/thread/test_singleton.ts | 44 +- src/test/thread/test_sleeps.ts | 34 +- src/test/thread/test_timed_singleton.ts | 14 +- .../thread/test_variadic_mutable_singleton.ts | 49 +- src/test/thread/test_variadic_singleton.ts | 44 +- src/test/utility/test_utilities.ts | 22 +- src/thread/Barrier.ts | 185 +- src/thread/ConditionVariable.ts | 272 +- src/thread/Latch.ts | 207 +- src/thread/MutableSingleton.ts | 249 +- src/thread/Mutex.ts | 55 +- src/thread/Semaphore.ts | 532 +-- src/thread/SharedLock.ts | 305 +- src/thread/SharedMutex.ts | 93 +- src/thread/SharedTimedMutex.ts | 525 ++- src/thread/Singleton.ts | 21 +- src/thread/TimedMutex.ts | 81 +- src/thread/TimedSingleton.ts | 54 +- src/thread/UniqueLock.ts | 294 +- src/thread/VariadicMutableSingleton.ts | 107 +- src/thread/VariadicSingleton.ts | 37 +- src/thread/VariadicTimedSingleton.ts | 83 +- src/thread/global.ts | 27 +- src/utility/Entry.ts | 80 +- src/utility/IPair.ts | 16 +- src/utility/Pair.ts | 107 +- src/utility/node.ts | 22 +- tsconfig.json | 126 +- 244 files changed, 20801 insertions(+), 21265 deletions(-) delete mode 100644 .prettierignore create mode 100644 .vscode/settings.json create mode 100644 prettier.config.js diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index d024da22..00000000 --- a/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -dist -node_modules - -README.md \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index 8d6b5446..45a7ef5d 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,31 +1,32 @@ { - // Use IntelliSense to learn about possible Node.js debug attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "type": "node", - "request": "launch", - "name": "TypeScript Test using TS-NODE", - "runtimeArgs": [ - "-r", - "ts-node/register" - ], - "args": [ - "${workspaceRoot}/src/test/index.ts" - ] - }, - { - "type": "node", - "request": "launch", - "name": "JavaScript Test using SourceMap", - "program": "${workspaceRoot}/test/index.js", - "cwd": "${workspaceRoot}", - - // TypeScript - "sourceMaps": true, - "outFiles": ["${workspaceRot}/**.js"] - } - ] + // Use IntelliSense to learn about possible Node.js debug attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "launch", + "name": "TypeScript Test using TS-NODE", + "runtimeArgs": [ + "-r", + "ts-node/register" + ], + "args": [ + "${workspaceRoot}/src/test/index.ts" + ] + }, + { + "type": "node", + "request": "launch", + "name": "JavaScript Test using SourceMap", + "program": "${workspaceRoot}/test/index.js", + "cwd": "${workspaceRoot}", + // TypeScript + "sourceMaps": true, + "outFiles": [ + "${workspaceRot}/**.js" + ] + } + ] } \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..78187193 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.tabSize": 2, + "editor.formatOnSave": true, + "[typescript][javascript][json]": { + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.codeActionsOnSave": { + "source.fixAll.eslint": "explicit" + }, + } +} \ No newline at end of file diff --git a/package.json b/package.json index 30b73c1f..3042d4cd 100644 --- a/package.json +++ b/package.json @@ -27,10 +27,11 @@ "devDependencies": { "@rollup/plugin-terser": "^0.4.4", "@rollup/plugin-typescript": "^11.1.6", + "@trivago/prettier-plugin-sort-imports": "^4.3.0", "@types/cli": "^0.11.19", "@types/node": "^14.6.3", "cli": "^1.0.1", - "prettier": "^2.7.1", + "prettier": "^2.8.8", "rimraf": "^3.0.2", "rollup": "^4.13.1", "source-map-support": "^0.5.21", diff --git a/prettier.config.js b/prettier.config.js new file mode 100644 index 00000000..038b7dbf --- /dev/null +++ b/prettier.config.js @@ -0,0 +1,12 @@ +module.exports = { + parser: "typescript", + printWidth: 80, + semi: true, + tabWidth: 2, + trailingComma: "all", + plugins: [require.resolve("@trivago/prettier-plugin-sort-imports")], + importOrder: ["", "^[./]"], + importOrderSeparation: true, + importOrderSortSpecifiers: true, + importOrderParserPlugins: ["decorators-legacy", "typescript"], +}; diff --git a/rollup.config.js b/rollup.config.js index f04fb199..f948ecc1 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -1,29 +1,29 @@ -const typescript = require('@rollup/plugin-typescript'); -const terser = require('@rollup/plugin-terser'); +const typescript = require("@rollup/plugin-typescript"); +const terser = require("@rollup/plugin-terser"); module.exports = { - input: './src/index.ts', - output: { - dir: 'lib', - format: 'esm', - entryFileNames: '[name].mjs', - sourcemap: true, - }, - plugins: [ - typescript({ - tsconfig: "tsconfig.json", - module: "ES2020", - target: "ES2020", - }), - terser({ - format: { - comments: 'some', - beautify: true, - ecma: '2020', - }, - compress: false, - mangle: false, - module: true, - }), - ] -}; \ No newline at end of file + input: "./src/index.ts", + output: { + dir: "lib", + format: "esm", + entryFileNames: "[name].mjs", + sourcemap: true, + }, + plugins: [ + typescript({ + tsconfig: "tsconfig.json", + module: "ES2020", + target: "ES2020", + }), + terser({ + format: { + comments: "some", + beautify: true, + ecma: "2020", + }, + compress: false, + mangle: false, + module: true, + }), + ], +}; diff --git a/src/algorithm/binary_search.ts b/src/algorithm/binary_search.ts index 7b952202..687d9de5 100644 --- a/src/algorithm/binary_search.ts +++ b/src/algorithm/binary_search.ts @@ -1,16 +1,16 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IForwardIterator } from "../iterator/IForwardIterator"; import { IPointer } from "../functional/IPointer"; -import { Pair } from "../utility/Pair"; - -import { Comparator } from "../internal/functional/Comparator"; -import { distance, advance } from "../iterator/global"; import { less } from "../functional/comparators"; +import { Comparator } from "../internal/functional/Comparator"; +import { IForwardIterator } from "../iterator/IForwardIterator"; +import { advance, distance } from "../iterator/global"; +import { Pair } from "../utility/Pair"; /* ========================================================= BINARY SEARCH @@ -26,27 +26,27 @@ import { less } from "../functional/comparators"; * @return Iterator to the first element equal or after the val. */ export function lower_bound< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - val: IPointer.ValueType, - comp: Comparator> = less, + first: ForwardIterator, + last: ForwardIterator, + val: IPointer.ValueType, + comp: Comparator> = less, ): ForwardIterator { - let count: number = distance(first, last); + let count: number = distance(first, last); - while (count > 0) { - const step: number = Math.floor(count / 2); - const it: ForwardIterator = advance(first, step); + while (count > 0) { + const step: number = Math.floor(count / 2); + const it: ForwardIterator = advance(first, step); - if (comp(it.value, val)) { - first = it.next(); - count -= step + 1; - } else count = step; - } - return first; + if (comp(it.value, val)) { + first = it.next(); + count -= step + 1; + } else count = step; + } + return first; } /** @@ -60,27 +60,27 @@ export function lower_bound< * @return Iterator to the first element after the key. */ export function upper_bound< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - val: IPointer.ValueType, - comp: Comparator> = less, + first: ForwardIterator, + last: ForwardIterator, + val: IPointer.ValueType, + comp: Comparator> = less, ): ForwardIterator { - let count: number = distance(first, last); + let count: number = distance(first, last); - while (count > 0) { - const step: number = Math.floor(count / 2); - const it: ForwardIterator = advance(first, step); + while (count > 0) { + const step: number = Math.floor(count / 2); + const it: ForwardIterator = advance(first, step); - if (!comp(val, it.value)) { - first = it.next(); - count -= step + 1; - } else count = step; - } - return first; + if (!comp(val, it.value)) { + first = it.next(); + count -= step + 1; + } else count = step; + } + return first; } /** @@ -94,19 +94,19 @@ export function upper_bound< * @return Pair of {@link lower_bound} and {@link upper_bound}. */ export function equal_range< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - val: IPointer.ValueType, - comp: Comparator> = less, + first: ForwardIterator, + last: ForwardIterator, + val: IPointer.ValueType, + comp: Comparator> = less, ): Pair { - first = lower_bound(first, last, val, comp); - const second: ForwardIterator = upper_bound(first, last, val, comp); + first = lower_bound(first, last, val, comp); + const second: ForwardIterator = upper_bound(first, last, val, comp); - return new Pair(first, second); + return new Pair(first, second); } /** @@ -120,16 +120,16 @@ export function equal_range< * @return Whether the value exists or not. */ export function binary_search< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - val: IPointer.ValueType, - comp: Comparator> = less, + first: ForwardIterator, + last: ForwardIterator, + val: IPointer.ValueType, + comp: Comparator> = less, ): boolean { - first = lower_bound(first, last, val, comp); + first = lower_bound(first, last, val, comp); - return !first.equals(last) && !comp(val, first.value); + return !first.equals(last) && !comp(val, first.value); } diff --git a/src/algorithm/heap.ts b/src/algorithm/heap.ts index d227f48b..244a6e60 100644 --- a/src/algorithm/heap.ts +++ b/src/algorithm/heap.ts @@ -1,15 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IRandomAccessIterator } from "../iterator/IRandomAccessIterator"; import { IPointer } from "../functional/IPointer"; - +import { less } from "../functional/comparators"; import { Comparator } from "../internal/functional/Comparator"; import { General } from "../internal/functional/General"; -import { less } from "../functional/comparators"; +import { IRandomAccessIterator } from "../iterator/IRandomAccessIterator"; import { advance, distance } from "../iterator/global"; /* ========================================================= @@ -28,34 +28,27 @@ import { advance, distance } from "../iterator/global"; * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function make_heap< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - last: RandomAccessIterator, - comp: Comparator> = less, + first: RandomAccessIterator, + last: RandomAccessIterator, + comp: Comparator> = less, ): void { - const heapSize: number = distance(first, last); - if (heapSize < 2) return; + const heapSize: number = distance(first, last); + if (heapSize < 2) return; - let parentPosition: number = ((heapSize - 2) >> 1) + 1; - do { - const temp: IPointer.ValueType = first.advance( - --parentPosition, - ).value; - _Adjust_heap( - first, - parentPosition, - heapSize, - parentPosition, - temp, - comp, - ); - } while (parentPosition !== 0); + let parentPosition: number = ((heapSize - 2) >> 1) + 1; + do { + const temp: IPointer.ValueType = first.advance( + --parentPosition, + ).value; + _Adjust_heap(first, parentPosition, heapSize, parentPosition, temp, comp); + } while (parentPosition !== 0); } /** @@ -66,19 +59,19 @@ export function make_heap< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function push_heap< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - last: RandomAccessIterator, - comp: Comparator> = less, + first: RandomAccessIterator, + last: RandomAccessIterator, + comp: Comparator> = less, ): void { - const temp: IPointer.ValueType = last.prev().value; - _Promote_heap(first, 0, distance(first, last) - 1, temp, comp); + const temp: IPointer.ValueType = last.prev().value; + _Promote_heap(first, 0, distance(first, last) - 1, temp, comp); } /** @@ -89,22 +82,22 @@ export function push_heap< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function pop_heap< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - last: RandomAccessIterator, - comp: Comparator> = less, + first: RandomAccessIterator, + last: RandomAccessIterator, + comp: Comparator> = less, ): void { - const bottom: RandomAccessIterator = last.prev(); - const temp: IPointer.ValueType = bottom.value; + const bottom: RandomAccessIterator = last.prev(); + const temp: IPointer.ValueType = bottom.value; - bottom.value = first.value; - _Adjust_heap(first, 0, distance(first, last) - 1, 0, temp, comp); + bottom.value = first.value; + _Adjust_heap(first, 0, distance(first, last) - 1, 0, temp, comp); } /* --------------------------------------------------------- @@ -120,19 +113,19 @@ export function pop_heap< * @return Whether the range is heap. */ export function is_heap< - RandomAccessIterator extends Readonly< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends Readonly< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - last: RandomAccessIterator, - comp: Comparator> = less, + first: RandomAccessIterator, + last: RandomAccessIterator, + comp: Comparator> = less, ): boolean { - const it = is_heap_until(first, last, comp); - return it.equals(last); + const it = is_heap_until(first, last, comp); + return it.equals(last); } /** @@ -145,27 +138,27 @@ export function is_heap< * @return Iterator to the first element not in heap order. */ export function is_heap_until< - RandomAccessIterator extends Readonly< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends Readonly< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - last: RandomAccessIterator, - comp: Comparator> = less, + first: RandomAccessIterator, + last: RandomAccessIterator, + comp: Comparator> = less, ): RandomAccessIterator { - let counter: number = 0; - for ( - let child = first.next(); - _Comp_it(child, last.index()); - child = child.next(), counter ^= 1 - ) { - if (comp(first.value, child.value)) return child; - first = advance(first, counter); - } - return last; + let counter: number = 0; + for ( + let child = first.next(); + _Comp_it(child, last.index()); + child = child.next(), counter ^= 1 + ) { + if (comp(first.value, child.value)) return child; + first = advance(first, counter); + } + return last; } /** @@ -176,87 +169,86 @@ export function is_heap_until< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function sort_heap< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - last: RandomAccessIterator, - comp: Comparator> = less, + first: RandomAccessIterator, + last: RandomAccessIterator, + comp: Comparator> = less, ): void { - for (; distance(first, last) > 1; last = last.prev()) - pop_heap(first, last, comp); + for (; distance(first, last) > 1; last = last.prev()) + pop_heap(first, last, comp); } /* --------------------------------------------------------- INTERNAL --------------------------------------------------------- */ function _Promote_heap< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - topPosition: number, - position: number, - value: IPointer.ValueType, - comp: Comparator>, + first: RandomAccessIterator, + topPosition: number, + position: number, + value: IPointer.ValueType, + comp: Comparator>, ): void { - for ( - let parentPosition: number = (position - 1) >> 1; - position > topPosition && - comp(first.advance(parentPosition).value, value); - parentPosition = (position - 1) >> 1 - ) { - first.advance(position).value = first.advance(parentPosition).value; - position = parentPosition; - } - first.advance(position).value = value; + for ( + let parentPosition: number = (position - 1) >> 1; + position > topPosition && comp(first.advance(parentPosition).value, value); + parentPosition = (position - 1) >> 1 + ) { + first.advance(position).value = first.advance(parentPosition).value; + position = parentPosition; + } + first.advance(position).value = value; } function _Adjust_heap< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - topPosition: number, - heapSize: number, - position: number, - value: IPointer.ValueType, - comp: Comparator>, + first: RandomAccessIterator, + topPosition: number, + heapSize: number, + position: number, + value: IPointer.ValueType, + comp: Comparator>, ): void { - let childPosition: number = 2 * position + 2; - for (; childPosition < heapSize; childPosition = 2 * childPosition + 2) { - if ( - comp( - first.advance(childPosition).value, - first.advance(childPosition - 1).value, - ) - ) - --childPosition; + let childPosition: number = 2 * position + 2; + for (; childPosition < heapSize; childPosition = 2 * childPosition + 2) { + if ( + comp( + first.advance(childPosition).value, + first.advance(childPosition - 1).value, + ) + ) + --childPosition; - first.advance(position).value = first.advance(childPosition).value; - position = childPosition; - } + first.advance(position).value = first.advance(childPosition).value; + position = childPosition; + } - if (childPosition === heapSize) { - first.advance(position).value = first.advance(childPosition - 1).value; - position = childPosition - 1; - } - _Promote_heap(first, topPosition, position, value, comp); + if (childPosition === heapSize) { + first.advance(position).value = first.advance(childPosition - 1).value; + position = childPosition - 1; + } + _Promote_heap(first, topPosition, position, value, comp); } function _Comp_it(x: any, y: any): boolean { - if (x.base instanceof Function) return y < x; - else return x < y; + if (x.base instanceof Function) return y < x; + else return x < y; } diff --git a/src/algorithm/iterations.ts b/src/algorithm/iterations.ts index 2e338c2c..38fc3986 100644 --- a/src/algorithm/iterations.ts +++ b/src/algorithm/iterations.ts @@ -1,17 +1,17 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IForwardIterator } from "../iterator/IForwardIterator"; import { IPointer } from "../functional/IPointer"; -import { Pair } from "../utility/Pair"; - +import { equal_to, less } from "../functional/comparators"; import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; import { UnaryPredicator } from "../internal/functional/UnaryPredicator"; -import { equal_to, less } from "../functional/comparators"; +import { IForwardIterator } from "../iterator/IForwardIterator"; import { advance, distance } from "../iterator/global"; +import { Pair } from "../utility/Pair"; /* ========================================================= ITERATIONS (NON-MODIFYING SEQUENCE) @@ -32,14 +32,14 @@ import { advance, distance } from "../iterator/global"; * @return The function *fn* itself. */ export function for_each< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - Func extends (val: IPointer.ValueType) => any, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + Func extends (val: IPointer.ValueType) => any, >(first: InputIterator, last: InputIterator, fn: Func): Func { - for (let it = first; !it.equals(last); it = it.next()) fn(it.value); + for (let it = first; !it.equals(last); it = it.next()) fn(it.value); - return fn; + return fn; } /** @@ -52,16 +52,16 @@ export function for_each< * @return Iterator advanced from *first* for *n* steps. */ export function for_each_n< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - Func extends (val: IPointer.ValueType) => any, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + Func extends (val: IPointer.ValueType) => any, >(first: InputIterator, n: number, fn: Func): InputIterator { - for (let i: number = 0; i < n; ++i) { - fn(first.value); - first = first.next(); - } - return first; + for (let i: number = 0; i < n; ++i) { + fn(first.value); + first = first.next(); + } + return first; } /* --------------------------------------------------------- @@ -77,18 +77,18 @@ export function for_each_n< * @return Whether the *pred* returns always `true` for all elements. */ export function all_of< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: UnaryPredicator>, + first: InputIterator, + last: InputIterator, + pred: UnaryPredicator>, ): boolean { - for (let it = first; !it.equals(last); it = it.next()) - if (pred(it.value) === false) return false; + for (let it = first; !it.equals(last); it = it.next()) + if (pred(it.value) === false) return false; - return true; + return true; } /** @@ -101,18 +101,18 @@ export function all_of< * @return Whether the *pred* returns at least a `true` for all elements. */ export function any_of< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: UnaryPredicator>, + first: InputIterator, + last: InputIterator, + pred: UnaryPredicator>, ): boolean { - for (let it = first; !it.equals(last); it = it.next()) - if (pred(it.value) === true) return true; + for (let it = first; !it.equals(last); it = it.next()) + if (pred(it.value) === true) return true; - return false; + return false; } /** @@ -125,15 +125,15 @@ export function any_of< * @return Whether the *pred* doesn't return `true` for all elements. */ export function none_of< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: UnaryPredicator>, + first: InputIterator, + last: InputIterator, + pred: UnaryPredicator>, ): boolean { - return !any_of(first, last, pred); + return !any_of(first, last, pred); } /** @@ -147,16 +147,16 @@ export function none_of< * @return Whether two ranges are equal. */ export function equal< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, ): boolean; /** @@ -170,45 +170,45 @@ export function equal< * @return Whether two ranges are equal. */ export function equal< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - pred: BinaryPredicator< - IPointer.ValueType, - IPointer.ValueType - >, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + pred: BinaryPredicator< + IPointer.ValueType, + IPointer.ValueType + >, ): boolean; export function equal< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - pred: BinaryPredicator< - IPointer.ValueType, - IPointer.ValueType - > = equal_to as any, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + pred: BinaryPredicator< + IPointer.ValueType, + IPointer.ValueType + > = equal_to as any, ): boolean { - while (!first1.equals(last1)) - if (!pred(first1.value, first2.value)) return false; - else { - first1 = first1.next(); - first2 = first2.next(); - } - return true; + while (!first1.equals(last1)) + if (!pred(first1.value, first2.value)) return false; + else { + first1 = first1.next(); + first2 = first2.next(); + } + return true; } /** @@ -223,29 +223,28 @@ export function equal< * @return Whether the 1st range precedes the 2nd. */ export function lexicographical_compare< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, >( - first1: Iterator1, - last1: Iterator1, - first2: Iterator2, - last2: Iterator2, - comp: BinaryPredicator> = less, + first1: Iterator1, + last1: Iterator1, + first2: Iterator2, + last2: Iterator2, + comp: BinaryPredicator> = less, ): boolean { - while (!first1.equals(last1)) - if (first2.equals(last2) || comp(first2.value, first1.value)) - return false; - else if (comp(first1.value, first2.value)) return true; - else { - first1 = first1.next(); - first2 = first2.next(); - } - - return !first2.equals(last2); + while (!first1.equals(last1)) + if (first2.equals(last2) || comp(first2.value, first1.value)) return false; + else if (comp(first1.value, first2.value)) return true; + else { + first1 = first1.next(); + first2 = first2.next(); + } + + return !first2.equals(last2); } /* --------------------------------------------------------- @@ -261,15 +260,15 @@ export function lexicographical_compare< * @return Iterator to the first element {@link equal to equal_to} the value. */ export function find< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - val: IPointer.ValueType, + first: InputIterator, + last: InputIterator, + val: IPointer.ValueType, ): InputIterator { - return find_if(first, last, (elem) => equal_to(elem, val)); + return find_if(first, last, (elem) => equal_to(elem, val)); } /** @@ -282,18 +281,18 @@ export function find< * @return Iterator to the first element *pred* returns `true`. */ export function find_if< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: UnaryPredicator>, + first: InputIterator, + last: InputIterator, + pred: UnaryPredicator>, ): InputIterator { - for (let it = first; !it.equals(last); it = it.next()) - if (pred(it.value)) return it; + for (let it = first; !it.equals(last); it = it.next()) + if (pred(it.value)) return it; - return last; + return last; } /** @@ -306,15 +305,15 @@ export function find_if< * @return Iterator to the first element *pred* returns `false`. */ export function find_if_not< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: UnaryPredicator>, + first: InputIterator, + last: InputIterator, + pred: UnaryPredicator>, ): InputIterator { - return find_if(first, last, (elem) => !pred(elem)); + return find_if(first, last, (elem) => !pred(elem)); } /** @@ -328,17 +327,17 @@ export function find_if_not< * @return Iterator to the first element of the last sub range. */ export function find_end< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, >( - first1: Iterator1, - last1: Iterator1, - first2: Iterator2, - last2: Iterator2, + first1: Iterator1, + last1: Iterator1, + first2: Iterator2, + last2: Iterator2, ): Iterator1; /** @@ -353,58 +352,58 @@ export function find_end< * @return Iterator to the first element of the last sub range. */ export function find_end< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, >( - first1: Iterator1, - last1: Iterator1, - first2: Iterator2, - last2: Iterator2, - pred: BinaryPredicator< - IPointer.ValueType, - IPointer.ValueType - >, + first1: Iterator1, + last1: Iterator1, + first2: Iterator2, + last2: Iterator2, + pred: BinaryPredicator< + IPointer.ValueType, + IPointer.ValueType + >, ): Iterator1; export function find_end< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, >( - first1: Iterator1, - last1: Iterator1, - first2: Iterator2, - last2: Iterator2, - pred: BinaryPredicator< - IPointer.ValueType, - IPointer.ValueType - > = equal_to, + first1: Iterator1, + last1: Iterator1, + first2: Iterator2, + last2: Iterator2, + pred: BinaryPredicator< + IPointer.ValueType, + IPointer.ValueType + > = equal_to, ): Iterator1 { - if (first2.equals(last2)) return last1; - - let ret: Iterator1 = last1; - for (; !first1.equals(last1); first1 = first1.next()) { - let it1: Iterator1 = first1; - let it2: Iterator2 = first2; - - while (pred(it1.value, it2.value)) { - it1 = it1.next(); - it2 = it2.next(); - - if (it2.equals(last2)) { - ret = first1; - break; - } else if (it1.equals(last1)) return ret; - } + if (first2.equals(last2)) return last1; + + let ret: Iterator1 = last1; + for (; !first1.equals(last1); first1 = first1.next()) { + let it1: Iterator1 = first1; + let it2: Iterator2 = first2; + + while (pred(it1.value, it2.value)) { + it1 = it1.next(); + it2 = it2.next(); + + if (it2.equals(last2)) { + ret = first1; + break; + } else if (it1.equals(last1)) return ret; } - return ret; + } + return ret; } /** @@ -418,17 +417,17 @@ export function find_end< * @return Iterator to the first element of the first sub range. */ export function find_first_of< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, >( - first1: Iterator1, - last1: Iterator1, - first2: Iterator2, - last2: Iterator2, + first1: Iterator1, + last1: Iterator1, + first2: Iterator2, + last2: Iterator2, ): Iterator1; /** @@ -443,45 +442,45 @@ export function find_first_of< * @return Iterator to the first element of the first sub range. */ export function find_first_of< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, >( - first1: Iterator1, - last1: Iterator1, - first2: Iterator2, - last2: Iterator2, - pred: BinaryPredicator< - IPointer.ValueType, - IPointer.ValueType - >, + first1: Iterator1, + last1: Iterator1, + first2: Iterator2, + last2: Iterator2, + pred: BinaryPredicator< + IPointer.ValueType, + IPointer.ValueType + >, ): Iterator1; export function find_first_of< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, >( - first1: Iterator1, - last1: Iterator1, - first2: Iterator2, - last2: Iterator2, - pred: BinaryPredicator< - IPointer.ValueType, - IPointer.ValueType - > = equal_to, + first1: Iterator1, + last1: Iterator1, + first2: Iterator2, + last2: Iterator2, + pred: BinaryPredicator< + IPointer.ValueType, + IPointer.ValueType + > = equal_to, ): Iterator1 { - for (; !first1.equals(last1); first1 = first1.next()) - for (let it = first2; !it.equals(last2); it = it.next()) - if (pred(first1.value, it.value)) return first1; + for (; !first1.equals(last1); first1 = first1.next()) + for (let it = first2; !it.equals(last2); it = it.next()) + if (pred(first1.value, it.value)) return first1; - return last1; + return last1; } /** @@ -494,25 +493,25 @@ export function find_first_of< * @return Iterator to the first element of adjacent find. */ export function adjacent_find< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: BinaryPredicator> = equal_to, + first: InputIterator, + last: InputIterator, + pred: BinaryPredicator> = equal_to, ): InputIterator { - if (!first.equals(last)) { - let next: InputIterator = first.next(); + if (!first.equals(last)) { + let next: InputIterator = first.next(); - while (!next.equals(last)) { - if (pred(first.value, next.value)) return first; + while (!next.equals(last)) { + if (pred(first.value, next.value)) return first; - first = first.next(); - next = next.next(); - } + first = first.next(); + next = next.next(); } - return last; + } + return last; } /** @@ -526,17 +525,17 @@ export function adjacent_find< * @return Iterator to the first element of the sub range. */ export function search< - ForwardIterator1 extends Readonly< - IForwardIterator, ForwardIterator1> - >, - ForwardIterator2 extends Readonly< - IForwardIterator, ForwardIterator2> - >, + ForwardIterator1 extends Readonly< + IForwardIterator, ForwardIterator1> + >, + ForwardIterator2 extends Readonly< + IForwardIterator, ForwardIterator2> + >, >( - first1: ForwardIterator1, - last1: ForwardIterator1, - first2: ForwardIterator2, - last2: ForwardIterator2, + first1: ForwardIterator1, + last1: ForwardIterator1, + first2: ForwardIterator2, + last2: ForwardIterator2, ): ForwardIterator1; /** @@ -551,55 +550,55 @@ export function search< * @return Iterator to the first element of the sub range. */ export function search< - ForwardIterator1 extends Readonly< - IForwardIterator, ForwardIterator1> - >, - ForwardIterator2 extends Readonly< - IForwardIterator, ForwardIterator2> - >, + ForwardIterator1 extends Readonly< + IForwardIterator, ForwardIterator1> + >, + ForwardIterator2 extends Readonly< + IForwardIterator, ForwardIterator2> + >, >( - first1: ForwardIterator1, - last1: ForwardIterator1, - first2: ForwardIterator2, - last2: ForwardIterator2, - pred: BinaryPredicator< - IPointer.ValueType, - IPointer.ValueType - >, + first1: ForwardIterator1, + last1: ForwardIterator1, + first2: ForwardIterator2, + last2: ForwardIterator2, + pred: BinaryPredicator< + IPointer.ValueType, + IPointer.ValueType + >, ): ForwardIterator1; export function search< - ForwardIterator1 extends Readonly< - IForwardIterator, ForwardIterator1> - >, - ForwardIterator2 extends Readonly< - IForwardIterator, ForwardIterator2> - >, + ForwardIterator1 extends Readonly< + IForwardIterator, ForwardIterator1> + >, + ForwardIterator2 extends Readonly< + IForwardIterator, ForwardIterator2> + >, >( - first1: ForwardIterator1, - last1: ForwardIterator1, - first2: ForwardIterator2, - last2: ForwardIterator2, - pred: BinaryPredicator< - IPointer.ValueType, - IPointer.ValueType - > = equal_to, + first1: ForwardIterator1, + last1: ForwardIterator1, + first2: ForwardIterator2, + last2: ForwardIterator2, + pred: BinaryPredicator< + IPointer.ValueType, + IPointer.ValueType + > = equal_to, ): ForwardIterator1 { - if (first2.equals(last2)) return first1; + if (first2.equals(last2)) return first1; - for (; !first1.equals(last1); first1 = first1.next()) { - let it1: ForwardIterator1 = first1; - let it2: ForwardIterator2 = first2; + for (; !first1.equals(last1); first1 = first1.next()) { + let it1: ForwardIterator1 = first1; + let it2: ForwardIterator2 = first2; - while (pred(it1.value, it2.value)) { - if (it2.equals(last2)) return first1; - else if (it1.equals(last1)) return last1; + while (pred(it1.value, it2.value)) { + if (it2.equals(last2)) return first1; + else if (it1.equals(last1)) return last1; - it1 = it1.next(); - it2 = it2.next(); - } + it1 = it1.next(); + it2 = it2.next(); } - return last1; + } + return last1; } /** @@ -614,32 +613,29 @@ export function search< * @return Iterator to the first element of the repetition. */ export function search_n< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - count: number, - val: IPointer.ValueType, - pred: BinaryPredicator> = equal_to, + first: ForwardIterator, + last: ForwardIterator, + count: number, + val: IPointer.ValueType, + pred: BinaryPredicator> = equal_to, ): ForwardIterator { - const limit: ForwardIterator = advance( - first, - distance(first, last) - count, - ); + const limit: ForwardIterator = advance(first, distance(first, last) - count); - for (; !first.equals(limit); first = first.next()) { - let it: ForwardIterator = first; - let i: number = 0; + for (; !first.equals(limit); first = first.next()) { + let it: ForwardIterator = first; + let i: number = 0; - while (pred(it.value, val)) { - it = it.next(); + while (pred(it.value, val)) { + it = it.next(); - if (++i === count) return first; - } + if (++i === count) return first; } - return last; + } + return last; } /** @@ -652,16 +648,16 @@ export function search_n< * @return A {@link Pair} of mismatched positions. */ export function mismatch< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, >( - first1: Iterator1, - last1: Iterator1, - first2: Iterator2, + first1: Iterator1, + last1: Iterator1, + first2: Iterator2, ): Pair; /** @@ -675,43 +671,43 @@ export function mismatch< * @return A {@link Pair} of mismatched positions. */ export function mismatch< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, >( - first1: Iterator1, - last1: Iterator1, - first2: Iterator2, - pred: BinaryPredicator< - IPointer.ValueType, - IPointer.ValueType - >, + first1: Iterator1, + last1: Iterator1, + first2: Iterator2, + pred: BinaryPredicator< + IPointer.ValueType, + IPointer.ValueType + >, ): Pair; export function mismatch< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, >( - first1: Iterator1, - last1: Iterator1, - first2: Iterator2, - pred: BinaryPredicator< - IPointer.ValueType, - IPointer.ValueType - > = equal_to, + first1: Iterator1, + last1: Iterator1, + first2: Iterator2, + pred: BinaryPredicator< + IPointer.ValueType, + IPointer.ValueType + > = equal_to, ): Pair { - while (!first1.equals(last1) && pred(first1.value, first2.value)) { - first1 = first1.next(); - first2 = first2.next(); - } - return new Pair(first1, first2); + while (!first1.equals(last1) && pred(first1.value, first2.value)) { + first1 = first1.next(); + first2 = first2.next(); + } + return new Pair(first1, first2); } /* --------------------------------------------------------- @@ -727,15 +723,15 @@ export function mismatch< * @return The matched count. */ export function count< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - val: IPointer.ValueType, + first: InputIterator, + last: InputIterator, + val: IPointer.ValueType, ): number { - return count_if(first, last, (elem) => equal_to(elem, val)); + return count_if(first, last, (elem) => equal_to(elem, val)); } /** @@ -748,18 +744,18 @@ export function count< * @return The matched count. */ export function count_if< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: UnaryPredicator>, + first: InputIterator, + last: InputIterator, + pred: UnaryPredicator>, ): number { - let ret: number = 0; + let ret: number = 0; - for (let it = first; !it.equals(last); it = it.next()) - if (pred(it.value)) ++ret; + for (let it = first; !it.equals(last); it = it.next()) + if (pred(it.value)) ++ret; - return ret; + return ret; } diff --git a/src/algorithm/mathematics.ts b/src/algorithm/mathematics.ts index 573fcd59..dc2c3936 100644 --- a/src/algorithm/mathematics.ts +++ b/src/algorithm/mathematics.ts @@ -1,24 +1,22 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IForwardIterator } from "../iterator/IForwardIterator"; -import { IBidirectionalIterator } from "../iterator/IBidirectionalIterator"; import { IPointer } from "../functional/IPointer"; - +import { equal_to, less } from "../functional/comparators"; +import { Comparator } from "../internal/functional/Comparator"; import { General } from "../internal/functional/General"; -import { Pair } from "../utility/Pair"; - -import { less, equal_to } from "../functional/comparators"; +import { Temporary } from "../internal/functional/Temporary"; +import { IBidirectionalIterator } from "../iterator/IBidirectionalIterator"; +import { IForwardIterator } from "../iterator/IForwardIterator"; import { advance, distance } from "../iterator/global"; -import { mismatch, find_if, count_if } from "./iterations"; +import { Pair } from "../utility/Pair"; +import { count_if, find_if, mismatch } from "./iterations"; import { iter_swap, reverse } from "./modifiers"; -import { Comparator } from "../internal/functional/Comparator"; -import { Temporary } from "../internal/functional/Temporary"; - /* ========================================================= MATHMATICS - MIN & MAX @@ -35,12 +33,12 @@ import { Temporary } from "../internal/functional/Temporary"; * @return The minimum value. */ export function min(items: T[], comp: Comparator = less): T { - let minimum: T = items[0]; + let minimum: T = items[0]; - for (let i: number = 1; i < items.length; ++i) - if (comp(items[i], minimum)) minimum = items[i]; + for (let i: number = 1; i < items.length; ++i) + if (comp(items[i], minimum)) minimum = items[i]; - return minimum; + return minimum; } /** @@ -52,12 +50,12 @@ export function min(items: T[], comp: Comparator = less): T { * @return The maximum value. */ export function max(items: T[], comp: Comparator = less): T { - let maximum: T = items[0]; + let maximum: T = items[0]; - for (let i: number = 1; i < items.length; ++i) - if (comp(maximum, items[i])) maximum = items[i]; + for (let i: number = 1; i < items.length; ++i) + if (comp(maximum, items[i])) maximum = items[i]; - return maximum; + return maximum; } /** @@ -69,14 +67,14 @@ export function max(items: T[], comp: Comparator = less): T { * @return A {@link Pair} of minimum & maximum values. */ export function minmax(items: T[], comp: Comparator = less): Pair { - let minimum: T = items[0]; - let maximum: T = items[0]; - - for (let i: number = 1; i < items.length; ++i) { - if (comp(items[i], minimum)) minimum = items[i]; - if (comp(maximum, items[i])) maximum = items[i]; - } - return new Pair(minimum, maximum); + let minimum: T = items[0]; + let maximum: T = items[0]; + + for (let i: number = 1; i < items.length; ++i) { + if (comp(items[i], minimum)) minimum = items[i]; + if (comp(maximum, items[i])) maximum = items[i]; + } + return new Pair(minimum, maximum); } /** @@ -89,21 +87,21 @@ export function minmax(items: T[], comp: Comparator = less): Pair { * @return Iterator to the minimum element. */ export function min_element< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - comp: Comparator> = less, + first: ForwardIterator, + last: ForwardIterator, + comp: Comparator> = less, ): ForwardIterator { - let smallest: ForwardIterator = first; - first = first.next(); + let smallest: ForwardIterator = first; + first = first.next(); - for (; !first.equals(last); first = first.next()) - if (comp(first.value, smallest.value)) smallest = first; + for (; !first.equals(last); first = first.next()) + if (comp(first.value, smallest.value)) smallest = first; - return smallest; + return smallest; } /** @@ -116,21 +114,21 @@ export function min_element< * @return Iterator to the maximum element. */ export function max_element< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - comp: Comparator> = less, + first: ForwardIterator, + last: ForwardIterator, + comp: Comparator> = less, ): ForwardIterator { - let largest: ForwardIterator = first; - first = first.next(); + let largest: ForwardIterator = first; + first = first.next(); - for (; !first.equals(last); first = first.next()) - if (comp(largest.value, first.value)) largest = first; + for (; !first.equals(last); first = first.next()) + if (comp(largest.value, first.value)) largest = first; - return largest; + return largest; } /** @@ -143,27 +141,27 @@ export function max_element< * @return A {@link Pair} of iterators to the minimum & maximum elements. */ export function minmax_element< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - comp: Comparator> = less, + first: ForwardIterator, + last: ForwardIterator, + comp: Comparator> = less, ): Pair { - let smallest: ForwardIterator = first; - let largest: ForwardIterator = first; - - first = first.next(); - for (; !first.equals(last); first = first.next()) { - if (comp(first.value, smallest.value)) - // first is less than the smallest. - smallest = first; - if (comp(largest.value, first.value)) - // first is not less than the largest. - largest = first; - } - return new Pair(smallest, largest); + let smallest: ForwardIterator = first; + let largest: ForwardIterator = first; + + first = first.next(); + for (; !first.equals(last); first = first.next()) { + if (comp(first.value, smallest.value)) + // first is less than the smallest. + smallest = first; + if (comp(largest.value, first.value)) + // first is not less than the largest. + largest = first; + } + return new Pair(smallest, largest); } /** @@ -177,7 +175,7 @@ export function minmax_element< * @return The clamp value. */ export function clamp(v: T, lo: T, hi: T, comp: Comparator = less): T { - return comp(v, lo) ? lo : comp(hi, v) ? hi : v; + return comp(v, lo) ? lo : comp(hi, v) ? hi : v; } /* --------------------------------------------------------- @@ -194,46 +192,42 @@ export function clamp(v: T, lo: T, hi: T, comp: Comparator = less): T { * @return Whether permutation or not. */ export function is_permutation< - ForwardIterator1 extends Readonly< - IForwardIterator, ForwardIterator1> - >, - ForwardIterator2 extends Readonly< - IForwardIterator, ForwardIterator2> - >, + ForwardIterator1 extends Readonly< + IForwardIterator, ForwardIterator1> + >, + ForwardIterator2 extends Readonly< + IForwardIterator, ForwardIterator2> + >, >( - first1: ForwardIterator1, - last1: ForwardIterator1, - first2: ForwardIterator2, - pred: Comparator> = equal_to, + first1: ForwardIterator1, + last1: ForwardIterator1, + first2: ForwardIterator2, + pred: Comparator> = equal_to, ): boolean { - // find the mismatched - const pair: Pair = ( - mismatch(first1, last1, first2, pred) - ); - first1 = pair.first; - first2 = pair.second; - - if (first1.equals(last1)) return true; - - const last2: ForwardIterator2 = advance( - first2, - distance(first1, last1), - ) as ForwardIterator2; - - for (let it = first1; !it.equals(last1); it = it.next()) { - const lambda = (val: IPointer.ValueType) => - pred(val, it.value); - - if (find_if(first1, it, lambda).equals(it)) { - const n: number = count_if( - first2, - last2, - lambda, - ); - if (n === 0 || count_if(it, last1, lambda) !== n) return false; - } + // find the mismatched + const pair: Pair = ( + mismatch(first1, last1, first2, pred) + ); + first1 = pair.first; + first2 = pair.second; + + if (first1.equals(last1)) return true; + + const last2: ForwardIterator2 = advance( + first2, + distance(first1, last1), + ) as ForwardIterator2; + + for (let it = first1; !it.equals(last1); it = it.next()) { + const lambda = (val: IPointer.ValueType) => + pred(val, it.value); + + if (find_if(first1, it, lambda).equals(it)) { + const n: number = count_if(first2, last2, lambda); + if (n === 0 || count_if(it, last1, lambda) !== n) return false; } - return true; + } + return true; } /** @@ -246,40 +240,40 @@ export function is_permutation< * @return Whether the transformation was meaningful. */ export function prev_permutation< - BidirectionalIterator extends General< - IBidirectionalIterator< - IPointer.ValueType, - BidirectionalIterator - > - >, + BidirectionalIterator extends General< + IBidirectionalIterator< + IPointer.ValueType, + BidirectionalIterator + > + >, >( - first: BidirectionalIterator, - last: BidirectionalIterator, - comp: Comparator> = less, + first: BidirectionalIterator, + last: BidirectionalIterator, + comp: Comparator> = less, ): boolean { - if (first.equals(last) === true) return false; + if (first.equals(last) === true) return false; - let previous: BidirectionalIterator = last.prev(); - if (first.equals(previous) === true) return false; + let previous: BidirectionalIterator = last.prev(); + if (first.equals(previous) === true) return false; - while (true) { - let x: BidirectionalIterator = previous; - previous = previous.prev(); + while (true) { + let x: BidirectionalIterator = previous; + previous = previous.prev(); - if (comp(x.value, previous.value) === true) { - let y: BidirectionalIterator = last.prev(); - while (comp(y.value, previous.value) === false) y = y.prev(); + if (comp(x.value, previous.value) === true) { + let y: BidirectionalIterator = last.prev(); + while (comp(y.value, previous.value) === false) y = y.prev(); - iter_swap(previous, y); - reverse(x, last); - return true; - } + iter_swap(previous, y); + reverse(x, last); + return true; + } - if (previous.equals(first) === true) { - reverse(first, last); - return false; - } + if (previous.equals(first) === true) { + reverse(first, last); + return false; } + } } /** @@ -292,38 +286,38 @@ export function prev_permutation< * @return Whether the transformation was meaningful. */ export function next_permutation< - BidirectionalIterator extends General< - IBidirectionalIterator< - IPointer.ValueType, - BidirectionalIterator - > - >, + BidirectionalIterator extends General< + IBidirectionalIterator< + IPointer.ValueType, + BidirectionalIterator + > + >, >( - first: BidirectionalIterator, - last: BidirectionalIterator, - comp: Comparator> = less, + first: BidirectionalIterator, + last: BidirectionalIterator, + comp: Comparator> = less, ): boolean { - if (first.equals(last) === true) return false; + if (first.equals(last) === true) return false; - let previous: BidirectionalIterator = last.prev(); - if (first.equals(previous) === true) return false; + let previous: BidirectionalIterator = last.prev(); + if (first.equals(previous) === true) return false; - while (true) { - const x: BidirectionalIterator = previous; - previous = previous.prev(); + while (true) { + const x: BidirectionalIterator = previous; + previous = previous.prev(); - if (comp(previous.value, x.value) === true) { - let y: BidirectionalIterator = last.prev(); - while (comp(previous.value, y.value) === false) y = y.prev(); + if (comp(previous.value, x.value) === true) { + let y: BidirectionalIterator = last.prev(); + while (comp(previous.value, y.value) === false) y = y.prev(); - iter_swap(previous, y); - reverse(x, last); - return true; - } + iter_swap(previous, y); + reverse(x, last); + return true; + } - if (previous.equals(first) === true) { - reverse(first, last); - return false; - } + if (previous.equals(first) === true) { + reverse(first, last); + return false; } + } } diff --git a/src/algorithm/merge.ts b/src/algorithm/merge.ts index f3f6ad89..18373605 100644 --- a/src/algorithm/merge.ts +++ b/src/algorithm/merge.ts @@ -1,22 +1,21 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IForwardIterator } from "../iterator/IForwardIterator"; -import { IBidirectionalIterator } from "../iterator/IBidirectionalIterator"; +import { Vector } from "../container/Vector"; import { IPointer } from "../functional/IPointer"; - +import { less } from "../functional/comparators"; +import { Comparator } from "../internal/functional/Comparator"; import { General } from "../internal/functional/General"; +import { Temporary } from "../internal/functional/Temporary"; import { Writeonly } from "../internal/functional/Writeonly"; -import { less } from "../functional/comparators"; -import { copy } from "./modifiers"; +import { IBidirectionalIterator } from "../iterator/IBidirectionalIterator"; +import { IForwardIterator } from "../iterator/IForwardIterator"; import { back_inserter } from "../iterator/factory"; - -import { Vector } from "../container/Vector"; -import { Temporary } from "../internal/functional/Temporary"; -import { Comparator } from "../internal/functional/Comparator"; +import { copy } from "./modifiers"; /* ========================================================= MERGE & SET OPERATIONS @@ -38,36 +37,36 @@ import { Comparator } from "../internal/functional/Comparator"; * @return Output Iterator of the last position by advancing. */ export function merge< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - last2: InputIterator2, - output: OutputIterator, - comp: Comparator> = less, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + last2: InputIterator2, + output: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - while (true) { - if (first1.equals(last1)) return copy(first2, last2, output); - else if (first2.equals(last2)) return copy(first1, last1, output); + while (true) { + if (first1.equals(last1)) return copy(first2, last2, output); + else if (first2.equals(last2)) return copy(first1, last1, output); - if (comp(first1.value, first2.value)) { - output.value = first1.value; - first1 = first1.next(); - } else { - output.value = first2.value; - first2 = first2.next(); - } - output = output.next(); + if (comp(first1.value, first2.value)) { + output.value = first1.value; + first1 = first1.next(); + } else { + output.value = first2.value; + first2 = first2.next(); } + output = output.next(); + } } /** @@ -79,23 +78,23 @@ export function merge< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function inplace_merge< - BidirectionalIterator extends General< - IBidirectionalIterator< - IPointer.ValueType, - BidirectionalIterator - > - >, + BidirectionalIterator extends General< + IBidirectionalIterator< + IPointer.ValueType, + BidirectionalIterator + > + >, >( - first: BidirectionalIterator, - middle: BidirectionalIterator, - last: BidirectionalIterator, - comp: Comparator> = less, + first: BidirectionalIterator, + middle: BidirectionalIterator, + last: BidirectionalIterator, + comp: Comparator> = less, ): void { - const vector: Vector> = - new Vector(); - merge(first, middle, middle, last, back_inserter(vector), comp); + const vector: Vector> = + new Vector(); + merge(first, middle, middle, last, back_inserter(vector), comp); - copy(vector.begin(), vector.end(), first); + copy(vector.begin(), vector.end(), first); } /* --------------------------------------------------------- @@ -113,28 +112,27 @@ export function inplace_merge< * @return Whether [first, last1) includes [first2, last2). */ export function includes< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - last2: InputIterator2, - comp: Comparator> = less, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + last2: InputIterator2, + comp: Comparator> = less, ): boolean { - while (!first2.equals(last2)) { - if (first1.equals(last1) || comp(first2.value, first1.value)) - return false; - else if (!comp(first1.value, first2.value)) first2 = first2.next(); + while (!first2.equals(last2)) { + if (first1.equals(last1) || comp(first2.value, first1.value)) return false; + else if (!comp(first1.value, first2.value)) first2 = first2.next(); - first1 = first1.next(); - } + first1 = first1.next(); + } - return true; + return true; } /** @@ -150,43 +148,43 @@ export function includes< * @return Output Iterator of the last position by advancing. */ export function set_union< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - last2: InputIterator2, - output: OutputIterator, - comp: Comparator> = less, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + last2: InputIterator2, + output: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - while (true) { - if (first1.equals(last1)) return copy(first2, last2, output); - else if (first2.equals(last2)) return copy(first1, last1, output); - - if (comp(first1.value, first2.value)) { - output.value = first1.value; - first1 = first1.next(); - } else if (comp(first2.value, first1.value)) { - output.value = first2.value; - first2 = first2.next(); - } else { - // equals - output.value = first1.value; + while (true) { + if (first1.equals(last1)) return copy(first2, last2, output); + else if (first2.equals(last2)) return copy(first1, last1, output); - first1 = first1.next(); - first2 = first2.next(); - } + if (comp(first1.value, first2.value)) { + output.value = first1.value; + first1 = first1.next(); + } else if (comp(first2.value, first1.value)) { + output.value = first2.value; + first2 = first2.next(); + } else { + // equals + output.value = first1.value; - output = output.next(); + first1 = first1.next(); + first2 = first2.next(); } + + output = output.next(); + } } /** @@ -202,34 +200,34 @@ export function set_union< * @return Output Iterator of the last position by advancing. */ export function set_intersection< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - last2: InputIterator2, - output: OutputIterator, - comp: Comparator> = less, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + last2: InputIterator2, + output: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - while (!first1.equals(last1) && !first2.equals(last2)) - if (comp(first1.value, first2.value)) first1 = first1.next(); - else if (comp(first2.value, first1.value)) first2 = first2.next(); - else { - output.value = first1.value; + while (!first1.equals(last1) && !first2.equals(last2)) + if (comp(first1.value, first2.value)) first1 = first1.next(); + else if (comp(first2.value, first1.value)) first2 = first2.next(); + else { + output.value = first1.value; - output = output.next(); - first1 = first1.next(); - first2 = first2.next(); - } - return output; + output = output.next(); + first1 = first1.next(); + first2 = first2.next(); + } + return output; } /** @@ -245,35 +243,35 @@ export function set_intersection< * @return Output Iterator of the last position by advancing. */ export function set_difference< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - last2: InputIterator2, - output: OutputIterator, - comp: Comparator> = less, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + last2: InputIterator2, + output: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - while (!first1.equals(last1) && !first2.equals(last2)) - if (comp(first1.value, first2.value)) { - output.value = first1.value; + while (!first1.equals(last1) && !first2.equals(last2)) + if (comp(first1.value, first2.value)) { + output.value = first1.value; - output = output.next(); - first1 = first1.next(); - } else if (comp(first2.value, first1.value)) first2 = first2.next(); - else { - first1 = first1.next(); - first2 = first2.next(); - } - return copy(first1, last1, output); + output = output.next(); + first1 = first1.next(); + } else if (comp(first2.value, first1.value)) first2 = first2.next(); + else { + first1 = first1.next(); + first2 = first2.next(); + } + return copy(first1, last1, output); } /** @@ -289,41 +287,41 @@ export function set_difference< * @return Output Iterator of the last position by advancing. */ export function set_symmetric_difference< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - last2: InputIterator2, - output: OutputIterator, - comp: Comparator> = less, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + last2: InputIterator2, + output: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - while (true) { - if (first1.equals(last1)) return copy(first2, last2, output); - else if (first2.equals(last2)) return copy(first1, last1, output); + while (true) { + if (first1.equals(last1)) return copy(first2, last2, output); + else if (first2.equals(last2)) return copy(first1, last1, output); - if (comp(first1.value, first2.value)) { - output.value = first1.value; + if (comp(first1.value, first2.value)) { + output.value = first1.value; - output = output.next(); - first1 = first1.next(); - } else if (comp(first2.value, first1.value)) { - output.value = first2.value; + output = output.next(); + first1 = first1.next(); + } else if (comp(first2.value, first1.value)) { + output.value = first2.value; - output = output.next(); - first2 = first2.next(); - } else { - // equals - first1 = first1.next(); - first2 = first2.next(); - } + output = output.next(); + first2 = first2.next(); + } else { + // equals + first1 = first1.next(); + first2 = first2.next(); } + } } diff --git a/src/algorithm/modifiers.ts b/src/algorithm/modifiers.ts index be8a97bb..c1867a02 100644 --- a/src/algorithm/modifiers.ts +++ b/src/algorithm/modifiers.ts @@ -1,46 +1,46 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IForwardIterator } from "../iterator/IForwardIterator"; -import { IBidirectionalIterator } from "../iterator/IBidirectionalIterator"; -import { IRandomAccessIterator } from "../iterator/IRandomAccessIterator"; import { IPointer } from "../functional/IPointer"; - -import { UnaryPredicator } from "../internal/functional/UnaryPredicator"; +import { equal_to } from "../functional/comparators"; import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; import { General } from "../internal/functional/General"; +import { UnaryPredicator } from "../internal/functional/UnaryPredicator"; import { Writeonly } from "../internal/functional/Writeonly"; -import { equal_to } from "../functional/comparators"; -import { randint } from "./random"; +import { IBidirectionalIterator } from "../iterator/IBidirectionalIterator"; +import { IForwardIterator } from "../iterator/IForwardIterator"; +import { IRandomAccessIterator } from "../iterator/IRandomAccessIterator"; import { advance } from "../iterator/global"; +import { randint } from "./random"; type UnaryOperatorInferrer< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, > = ( - val: IPointer.ValueType, + val: IPointer.ValueType, ) => IPointer.ValueType; type BinaryOperatorInferrer< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, > = ( - x: IPointer.ValueType, - y: IPointer.ValueType, + x: IPointer.ValueType, + y: IPointer.ValueType, ) => IPointer.ValueType; /* ========================================================= @@ -62,22 +62,22 @@ type BinaryOperatorInferrer< * @return Output Iterator of the last position by advancing. */ export function copy< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, + first: InputIterator, + last: InputIterator, + output: OutputIterator, ): OutputIterator { - for (; !first.equals(last); first = first.next()) { - output.value = first.value; - output = output.next(); - } - return output; + for (; !first.equals(last); first = first.next()) { + output.value = first.value; + output = output.next(); + } + return output; } /** @@ -90,20 +90,20 @@ export function copy< * @return Output Iterator of the last position by advancing. */ export function copy_n< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >(first: InputIterator, n: number, output: OutputIterator): OutputIterator { - for (let i: number = 0; i < n; ++i) { - output.value = first.value; + for (let i: number = 0; i < n; ++i) { + output.value = first.value; - first = first.next(); - output = output.next(); - } - return output; + first = first.next(); + output = output.next(); + } + return output; } /** @@ -117,25 +117,25 @@ export function copy_n< * @return Output Iterator of the last position by advancing. */ export function copy_if< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - pred: UnaryPredicator>, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + pred: UnaryPredicator>, ): OutputIterator { - for (; !first.equals(last); first = first.next()) { - if (!pred(first.value)) continue; + for (; !first.equals(last); first = first.next()) { + if (!pred(first.value)) continue; - output.value = first.value; - output = output.next(); - } - return output; + output.value = first.value; + output = output.next(); + } + return output; } /** @@ -148,29 +148,26 @@ export function copy_if< * @return Output Iterator of the last position by advancing. */ export function copy_backward< - InputIterator extends Readonly< - IBidirectionalIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IBidirectionalIterator< - IPointer.ValueType, - OutputIterator - > - >, + InputIterator extends Readonly< + IBidirectionalIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IBidirectionalIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, + first: InputIterator, + last: InputIterator, + output: OutputIterator, ): OutputIterator { - last = last.prev(); + last = last.prev(); - while (!last.equals(first)) { - last = last.prev(); - output = output.prev(); + while (!last.equals(first)) { + last = last.prev(); + output = output.prev(); - output.value = last.value; - } - return output; + output.value = last.value; + } + return output; } /** @@ -183,15 +180,15 @@ export function copy_backward< * @return Output Iterator of the last position by advancing. */ export function fill< - ForwardIterator extends Writeonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Writeonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - val: IPointer.ValueType, + first: ForwardIterator, + last: ForwardIterator, + val: IPointer.ValueType, ): void { - for (; !first.equals(last); first = first.next()) first.value = val; + for (; !first.equals(last); first = first.next()) first.value = val; } /** @@ -204,19 +201,19 @@ export function fill< * @return Output Iterator of the last position by advancing. */ export function fill_n< - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: OutputIterator, - n: number, - val: IPointer.ValueType, + first: OutputIterator, + n: number, + val: IPointer.ValueType, ): OutputIterator { - for (let i: number = 0; i < n; ++i) { - first.value = val; - first = first.next(); - } - return first; + for (let i: number = 0; i < n; ++i) { + first.value = val; + first = first.next(); + } + return first; } /** @@ -230,17 +227,17 @@ export function fill_n< * @return Output Iterator of the last position by advancing. */ export function transform< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - result: OutputIterator, - op: UnaryOperatorInferrer, + first: InputIterator, + last: InputIterator, + result: OutputIterator, + op: UnaryOperatorInferrer, ): OutputIterator; /** @@ -255,78 +252,78 @@ export function transform< * @return Output Iterator of the last position by advancing. */ export function transform< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - result: OutputIterator, - op: BinaryOperatorInferrer, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + result: OutputIterator, + op: BinaryOperatorInferrer, ): OutputIterator; export function transform(...args: any[]): any { - if (args.length === 4) return (_Unary_transform as Function)(...args); - // args: #5 - else return (_Binary_transform as Function)(...args); + if (args.length === 4) return (_Unary_transform as Function)(...args); + // args: #5 + else return (_Binary_transform as Function)(...args); } function _Unary_transform< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - result: OutputIterator, - op: UnaryOperatorInferrer, + first: InputIterator, + last: InputIterator, + result: OutputIterator, + op: UnaryOperatorInferrer, ): OutputIterator { - for (; !first.equals(last); first = first.next()) { - result.value = op(first.value); - result = result.next(); - } - return result; + for (; !first.equals(last); first = first.next()) { + result.value = op(first.value); + result = result.next(); + } + return result; } function _Binary_transform< - InputIterator1 extends Readonly< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends Readonly< - IForwardIterator, InputIterator2> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator1 extends Readonly< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends Readonly< + IForwardIterator, InputIterator2> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - result: OutputIterator, - binary_op: BinaryOperatorInferrer< - InputIterator1, - InputIterator2, - OutputIterator - >, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + result: OutputIterator, + binary_op: BinaryOperatorInferrer< + InputIterator1, + InputIterator2, + OutputIterator + >, ): OutputIterator { - while (!first1.equals(last1)) { - result.value = binary_op(first1.value, first2.value); - - first1 = first1.next(); - first2 = first2.next(); - result = result.next(); - } - return result; + while (!first1.equals(last1)) { + result.value = binary_op(first1.value, first2.value); + + first1 = first1.next(); + first2 = first2.next(); + result = result.next(); + } + return result; } /** @@ -337,15 +334,15 @@ function _Binary_transform< * @param gen The generator function. */ export function generate< - ForwardIterator extends Writeonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Writeonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - gen: () => IPointer.ValueType, + first: ForwardIterator, + last: ForwardIterator, + gen: () => IPointer.ValueType, ): void { - for (; !first.equals(last); first = first.next()) first.value = gen(); + for (; !first.equals(last); first = first.next()) first.value = gen(); } /** @@ -358,19 +355,19 @@ export function generate< * @return Forward Iterator to the last position by advancing. */ export function generate_n< - ForwardIterator extends Writeonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Writeonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - n: number, - gen: () => IPointer.ValueType, + first: ForwardIterator, + n: number, + gen: () => IPointer.ValueType, ): ForwardIterator { - while (n-- > 0) { - first.value = gen(); - first = first.next(); - } - return first; + while (n-- > 0) { + first.value = gen(); + first = first.next(); + } + return first; } /* --------------------------------------------------------- @@ -386,22 +383,22 @@ export function generate_n< * @returns Whether unique or not. */ export function is_unique< - InputIterator extends General< - IForwardIterator, InputIterator> - >, + InputIterator extends General< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: BinaryPredicator> = equal_to, + first: InputIterator, + last: InputIterator, + pred: BinaryPredicator> = equal_to, ): boolean { - if (first.equals(last)) return true; + if (first.equals(last)) return true; - let next: InputIterator = first.next(); - for (; !next.equals(last); next = next.next()) { - if (pred(first.value, next.value) === true) return false; - first = first.next(); - } - return true; + let next: InputIterator = first.next(); + for (; !next.equals(last); next = next.next()) { + if (pred(first.value, next.value) === true) return false; + first = first.next(); + } + return true; } /** @@ -414,23 +411,23 @@ export function is_unique< * @return Input iterator to the last element not removed. */ export function unique< - InputIterator extends General< - IForwardIterator, InputIterator> - >, + InputIterator extends General< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: BinaryPredicator> = equal_to, + first: InputIterator, + last: InputIterator, + pred: BinaryPredicator> = equal_to, ): InputIterator { - if (first.equals(last)) return last; - - let ret: InputIterator = first; - for (first = first.next(); !first.equals(last); first = first.next()) - if (!pred(ret.value, first.value)) { - ret = ret.next(); - ret.value = first.value; - } - return ret.next(); + if (first.equals(last)) return last; + + let ret: InputIterator = first; + for (first = first.next(); !first.equals(last); first = first.next()) + if (!pred(ret.value, first.value)) { + ret = ret.next(); + ret.value = first.value; + } + return ret.next(); } /** @@ -444,29 +441,29 @@ export function unique< * @return Output Iterator of the last position by advancing. */ export function unique_copy< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - pred: BinaryPredicator> = equal_to, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + pred: BinaryPredicator> = equal_to, ): OutputIterator { - if (first.equals(last)) return output; + if (first.equals(last)) return output; - output.value = first.value; - first = first.next(); + output.value = first.value; + first = first.next(); - for (; !first.equals(last); first = first.next()) - if (!pred(first.value, output.value)) { - output = output.next(); - output.value = first.value; - } - return output.next(); + for (; !first.equals(last); first = first.next()) + if (!pred(first.value, output.value)) { + output = output.next(); + output.value = first.value; + } + return output.next(); } /** @@ -479,15 +476,15 @@ export function unique_copy< * @return Iterator tho the last element not removed. */ export function remove< - InputIterator extends General< - IForwardIterator, InputIterator> - >, + InputIterator extends General< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - val: IPointer.ValueType, + first: InputIterator, + last: InputIterator, + val: IPointer.ValueType, ): InputIterator { - return remove_if(first, last, (elem) => equal_to(elem, val)); + return remove_if(first, last, (elem) => equal_to(elem, val)); } /** @@ -500,24 +497,24 @@ export function remove< * @return Iterator tho the last element not removed. */ export function remove_if< - InputIterator extends General< - IForwardIterator, InputIterator> - >, + InputIterator extends General< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: UnaryPredicator>, + first: InputIterator, + last: InputIterator, + pred: UnaryPredicator>, ): InputIterator { - let ret: InputIterator = first; - - while (!first.equals(last)) { - if (!pred(first.value)) { - ret.value = first.value; - ret = ret.next(); - } - first = first.next(); + let ret: InputIterator = first; + + while (!first.equals(last)) { + if (!pred(first.value)) { + ret.value = first.value; + ret = ret.next(); } - return ret; + first = first.next(); + } + return ret; } /** @@ -531,19 +528,19 @@ export function remove_if< * @return Output Iterator of the last position by advancing. */ export function remove_copy< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - val: IPointer.ValueType, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + val: IPointer.ValueType, ): OutputIterator { - return remove_copy_if(first, last, output, (elem) => equal_to(elem, val)); + return remove_copy_if(first, last, output, (elem) => equal_to(elem, val)); } /** @@ -557,26 +554,26 @@ export function remove_copy< * @return Output Iterator of the last position by advancing. */ export function remove_copy_if< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - pred: UnaryPredicator>, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + pred: UnaryPredicator>, ): OutputIterator { - for (; !first.equals(last); first = first.next()) { - if (pred(first.value)) continue; + for (; !first.equals(last); first = first.next()) { + if (pred(first.value)) continue; - output.value = first.value; - output = output.next(); - } + output.value = first.value; + output = output.next(); + } - return output; + return output; } /* --------------------------------------------------------- @@ -591,16 +588,16 @@ export function remove_copy_if< * @param new_val Specific value to be changed. */ export function replace< - InputIterator extends General< - IForwardIterator, InputIterator> - >, + InputIterator extends General< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - old_val: IPointer.ValueType, - new_val: IPointer.ValueType, + first: InputIterator, + last: InputIterator, + old_val: IPointer.ValueType, + new_val: IPointer.ValueType, ): void { - return replace_if(first, last, (elem) => equal_to(elem, old_val), new_val); + return replace_if(first, last, (elem) => equal_to(elem, old_val), new_val); } /** @@ -612,17 +609,17 @@ export function replace< * @param new_val Specific value to be changed. */ export function replace_if< - InputIterator extends General< - IForwardIterator, InputIterator> - >, + InputIterator extends General< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - pred: UnaryPredicator>, - new_val: IPointer.ValueType, + first: InputIterator, + last: InputIterator, + pred: UnaryPredicator>, + new_val: IPointer.ValueType, ): void { - for (let it = first; !it.equals(last); it = it.next()) - if (pred(it.value) === true) it.value = new_val; + for (let it = first; !it.equals(last); it = it.next()) + if (pred(it.value) === true) it.value = new_val; } /** @@ -637,26 +634,26 @@ export function replace_if< * @return Output Iterator of the last position by advancing. */ export function replace_copy< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - old_val: IPointer.ValueType, - new_val: IPointer.ValueType, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + old_val: IPointer.ValueType, + new_val: IPointer.ValueType, ): OutputIterator { - return replace_copy_if( - first, - last, - output, - (elem) => equal_to(elem, old_val), - new_val, - ); + return replace_copy_if( + first, + last, + output, + (elem) => equal_to(elem, old_val), + new_val, + ); } /** @@ -671,27 +668,27 @@ export function replace_copy< * @return Output Iterator of the last position by advancing. */ export function replace_copy_if< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - result: OutputIterator, - pred: UnaryPredicator>, - new_val: IPointer.ValueType, + first: InputIterator, + last: InputIterator, + result: OutputIterator, + pred: UnaryPredicator>, + new_val: IPointer.ValueType, ): OutputIterator { - for (; !first.equals(last); first = first.next()) { - if (pred(first.value)) result.value = new_val; - else result.value = first.value; + for (; !first.equals(last); first = first.next()) { + if (pred(first.value)) result.value = new_val; + else result.value = first.value; - result = result.next(); - } + result = result.next(); + } - return result; + return result; } /** @@ -701,14 +698,14 @@ export function replace_copy_if< * @param y Forward iterator to swap its value. */ export function iter_swap< - ForwardIterator1 extends General< - IForwardIterator, ForwardIterator1> - >, - ForwardIterator2 extends General< - IForwardIterator, ForwardIterator2> - >, + ForwardIterator1 extends General< + IForwardIterator, ForwardIterator1> + >, + ForwardIterator2 extends General< + IForwardIterator, ForwardIterator2> + >, >(x: ForwardIterator1, y: ForwardIterator2): void { - [x.value, y.value] = [y.value, x.value]; + [x.value, y.value] = [y.value, x.value]; } /** @@ -721,22 +718,22 @@ export function iter_swap< * @return Forward Iterator of the last position of the 2nd range by advancing. */ export function swap_ranges< - ForwardIterator1 extends General< - IForwardIterator, ForwardIterator1> - >, - ForwardIterator2 extends General< - IForwardIterator, ForwardIterator2> - >, + ForwardIterator1 extends General< + IForwardIterator, ForwardIterator1> + >, + ForwardIterator2 extends General< + IForwardIterator, ForwardIterator2> + >, >( - first1: ForwardIterator1, - last1: ForwardIterator1, - first2: ForwardIterator2, + first1: ForwardIterator1, + last1: ForwardIterator1, + first2: ForwardIterator2, ): ForwardIterator2 { - for (; !first1.equals(last1); first1 = first1.next()) { - iter_swap(first1, first2); - first2 = first2.next(); - } - return first2; + for (; !first1.equals(last1); first1 = first1.next()) { + iter_swap(first1, first2); + first2 = first2.next(); + } + return first2; } /* --------------------------------------------------------- @@ -749,21 +746,21 @@ export function swap_ranges< * @param last Bidirectional iterator of the last position. */ export function reverse< - BidirectionalIterator extends General< - IBidirectionalIterator< - IPointer.ValueType, - BidirectionalIterator - > - >, + BidirectionalIterator extends General< + IBidirectionalIterator< + IPointer.ValueType, + BidirectionalIterator + > + >, >(first: BidirectionalIterator, last: BidirectionalIterator): void { - // first !== last && first !== --last - while ( - first.equals(last) === false && - first.equals((last = last.prev())) === false - ) { - iter_swap(first, last); - first = first.next(); - } + // first !== last && first !== --last + while ( + first.equals(last) === false && + first.equals((last = last.prev())) === false + ) { + iter_swap(first, last); + first = first.next(); + } } /** @@ -776,51 +773,45 @@ export function reverse< * @return Output Iterator of the last position by advancing. */ export function reverse_copy< - BidirectionalIterator extends Readonly< - IBidirectionalIterator< - IPointer.ValueType, - BidirectionalIterator - > - >, - OutputIterator extends Writeonly< - IForwardIterator< - IPointer.ValueType, - OutputIterator - > - >, + BidirectionalIterator extends Readonly< + IBidirectionalIterator< + IPointer.ValueType, + BidirectionalIterator + > + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: BidirectionalIterator, - last: BidirectionalIterator, - output: OutputIterator, + first: BidirectionalIterator, + last: BidirectionalIterator, + output: OutputIterator, ): OutputIterator { - while (!last.equals(first)) { - last = last.prev(); + while (!last.equals(first)) { + last = last.prev(); - output.value = last.value; - output = output.next(); - } - return output; + output.value = last.value; + output = output.next(); + } + return output; } export function shift_left< - ForwardIterator extends General< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends General< + IForwardIterator, ForwardIterator> + >, >(first: ForwardIterator, last: ForwardIterator, n: number): ForwardIterator { - const mid = advance(first, n); - return copy(mid, last, first); + const mid = advance(first, n); + return copy(mid, last, first); } export function shift_right< - ForwardIterator extends General< - IBidirectionalIterator< - IPointer.ValueType, - ForwardIterator - > - >, + ForwardIterator extends General< + IBidirectionalIterator, ForwardIterator> + >, >(first: ForwardIterator, last: ForwardIterator, n: number): ForwardIterator { - const mid = advance(last, -n); - return copy_backward(first, mid, last); + const mid = advance(last, -n); + return copy_backward(first, mid, last); } /** @@ -833,21 +824,21 @@ export function shift_right< * @return Input iterator of the final position in the left side; *middle*. */ export function rotate< - InputIterator extends General< - IForwardIterator, InputIterator> - >, + InputIterator extends General< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - middle: InputIterator, - last: InputIterator, + first: InputIterator, + middle: InputIterator, + last: InputIterator, ): InputIterator { - while (!first.equals(middle) && !middle.equals(last)) { - iter_swap(first, middle); + while (!first.equals(middle) && !middle.equals(last)) { + iter_swap(first, middle); - first = first.next(); - middle = middle.next(); - } - return first; + first = first.next(); + middle = middle.next(); + } + return first; } /** @@ -861,20 +852,20 @@ export function rotate< * @return Output Iterator of the last position by advancing. */ export function rotate_copy< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: ForwardIterator, - middle: ForwardIterator, - last: ForwardIterator, - output: OutputIterator, + first: ForwardIterator, + middle: ForwardIterator, + last: ForwardIterator, + output: OutputIterator, ): OutputIterator { - output = copy(middle, last, output); - return copy(first, middle, output); + output = copy(middle, last, output); + return copy(first, middle, output); } /** @@ -884,15 +875,15 @@ export function rotate_copy< * @param last Random access iteartor of the last position. */ export function shuffle< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >(first: RandomAccessIterator, last: RandomAccessIterator): void { - for (let it = first; !it.equals(last); it = it.next()) { - const rand_index: number = randint(first.index(), last.index() - 1); - if (it.index() !== rand_index) iter_swap(it, first.advance(rand_index)); - } + for (let it = first; !it.equals(last); it = it.next()) { + const rand_index: number = randint(first.index(), last.index() - 1); + if (it.index() !== rand_index) iter_swap(it, first.advance(rand_index)); + } } diff --git a/src/algorithm/partition.ts b/src/algorithm/partition.ts index ba343c18..038fa1e3 100644 --- a/src/algorithm/partition.ts +++ b/src/algorithm/partition.ts @@ -1,19 +1,19 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IForwardIterator } from "../iterator/IForwardIterator"; -import { IBidirectionalIterator } from "../iterator/IBidirectionalIterator"; import { IPointer } from "../functional/IPointer"; - import { General } from "../internal/functional/General"; -import { Pair } from "../utility/Pair"; import { UnaryPredicator } from "../internal/functional/UnaryPredicator"; import { Writeonly } from "../internal/functional/Writeonly"; +import { IBidirectionalIterator } from "../iterator/IBidirectionalIterator"; +import { IForwardIterator } from "../iterator/IForwardIterator"; +import { advance, distance } from "../iterator/global"; +import { Pair } from "../utility/Pair"; import { iter_swap } from "./modifiers"; -import { distance, advance } from "../iterator/global"; /* ========================================================= PARTITION @@ -28,20 +28,20 @@ import { distance, advance } from "../iterator/global"; * @return Whether the range is partition or not. */ export function is_partitioned< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - pred: UnaryPredicator>, + first: ForwardIterator, + last: ForwardIterator, + pred: UnaryPredicator>, ): boolean { - while (!first.equals(last) && pred(first.value)) first = first.next(); + while (!first.equals(last) && pred(first.value)) first = first.next(); - for (; !first.equals(last); first = first.next()) - if (pred(first.value)) return false; + for (; !first.equals(last); first = first.next()) + if (pred(first.value)) return false; - return true; + return true; } /** @@ -54,26 +54,26 @@ export function is_partitioned< * @return Iterator to the first element of the second section. */ export function partition_point< - ForwardIterator extends Readonly< - IForwardIterator, ForwardIterator> - >, + ForwardIterator extends Readonly< + IForwardIterator, ForwardIterator> + >, >( - first: ForwardIterator, - last: ForwardIterator, - pred: UnaryPredicator>, + first: ForwardIterator, + last: ForwardIterator, + pred: UnaryPredicator>, ): ForwardIterator { - let n: number = distance(first, last); + let n: number = distance(first, last); - while (n > 0) { - const step: number = Math.floor(n / 2); - const it: ForwardIterator = advance(first, step); + while (n > 0) { + const step: number = Math.floor(n / 2); + const it: ForwardIterator = advance(first, step); - if (pred(it.value)) { - first = it.next(); - n -= step + 1; - } else n = step; - } - return first; + if (pred(it.value)) { + first = it.next(); + n -= step + 1; + } else n = step; + } + return first; } /** @@ -86,18 +86,18 @@ export function partition_point< * @return Iterator to the first element of the second section. */ export function partition< - BidirectionalIterator extends General< - IBidirectionalIterator< - IPointer.ValueType, - BidirectionalIterator - > - >, + BidirectionalIterator extends General< + IBidirectionalIterator< + IPointer.ValueType, + BidirectionalIterator + > + >, >( - first: BidirectionalIterator, - last: BidirectionalIterator, - pred: UnaryPredicator>, + first: BidirectionalIterator, + last: BidirectionalIterator, + pred: UnaryPredicator>, ): BidirectionalIterator { - return stable_partition(first, last, pred); + return stable_partition(first, last, pred); } /** @@ -110,32 +110,32 @@ export function partition< * @return Iterator to the first element of the second section. */ export function stable_partition< - BidirectionalIterator extends General< - IBidirectionalIterator< - IPointer.ValueType, - BidirectionalIterator - > - >, + BidirectionalIterator extends General< + IBidirectionalIterator< + IPointer.ValueType, + BidirectionalIterator + > + >, >( - first: BidirectionalIterator, - last: BidirectionalIterator, - pred: UnaryPredicator>, + first: BidirectionalIterator, + last: BidirectionalIterator, + pred: UnaryPredicator>, ): BidirectionalIterator { - while (!first.equals(last) && pred(first.value)) { - while (pred(first.value)) { - first = first.next(); - if (first.equals(last)) return first; - } + while (!first.equals(last) && pred(first.value)) { + while (pred(first.value)) { + first = first.next(); + if (first.equals(last)) return first; + } - do { - last = last.prev(); - if (first.equals(last)) return first; - } while (!pred(last.value)); + do { + last = last.prev(); + if (first.equals(last)) return first; + } while (!pred(last.value)); - iter_swap(first, last); - first = first.next(); - } - return last; + iter_swap(first, last); + first = first.next(); + } + return last; } /** @@ -150,29 +150,29 @@ export function stable_partition< * @return Iterator to the first element of the second section. */ export function partition_copy< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator1 extends Writeonly< - IForwardIterator, OutputIterator1> - >, - OutputIterator2 extends Writeonly< - IForwardIterator, OutputIterator2> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator1 extends Writeonly< + IForwardIterator, OutputIterator1> + >, + OutputIterator2 extends Writeonly< + IForwardIterator, OutputIterator2> + >, >( - first: InputIterator, - last: InputIterator, - output_true: OutputIterator1, - output_false: OutputIterator2, - pred: UnaryPredicator>, + first: InputIterator, + last: InputIterator, + output_true: OutputIterator1, + output_false: OutputIterator2, + pred: UnaryPredicator>, ): Pair { - for (; !first.equals(last); first = first.next()) - if (pred(first.value)) { - output_true.value = first.value; - output_true = output_true.next(); - } else { - output_false.value = first.value; - output_false = output_false.next(); - } - return new Pair(output_true, output_false); + for (; !first.equals(last); first = first.next()) + if (pred(first.value)) { + output_true.value = first.value; + output_true = output_true.next(); + } else { + output_false.value = first.value; + output_false = output_false.next(); + } + return new Pair(output_true, output_false); } diff --git a/src/algorithm/random.ts b/src/algorithm/random.ts index 8ad0a986..62c1f12d 100644 --- a/src/algorithm/random.ts +++ b/src/algorithm/random.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IForwardIterator } from "../iterator/IForwardIterator"; -import { IPointer } from "../functional/IPointer"; import { Vector } from "../container/Vector"; - +import { IPointer } from "../functional/IPointer"; import { Writeonly } from "../internal/functional/Writeonly"; +import { IForwardIterator } from "../iterator/IForwardIterator"; import { advance, distance } from "../iterator/global"; import { sort } from "./sorting"; @@ -21,8 +21,8 @@ import { sort } from "./sorting"; * @return A random integer between [x, y]. */ export function randint(x: number, y: number): number { - const rand: number = Math.random() * (y - x + 1); - return Math.floor(rand) + x; + const rand: number = Math.random() * (y - x + 1); + return Math.floor(rand) + x; } /** @@ -36,49 +36,49 @@ export function randint(x: number, y: number): number { * @return Output Iterator of the last position by advancing. */ export function sample< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - n: number, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + n: number, ): OutputIterator { - // GENERATE REMAINDERS - const step: number = distance(first, last); - const remainders: number[] = []; + // GENERATE REMAINDERS + const step: number = distance(first, last); + const remainders: number[] = []; - for (let i: number = 0; i < step; ++i) remainders.push(i); + for (let i: number = 0; i < step; ++i) remainders.push(i); - //---- - // CONSTRUCT INDEXES - //---- - const advances: Vector = new Vector(); - n = Math.min(n, step); + //---- + // CONSTRUCT INDEXES + //---- + const advances: Vector = new Vector(); + n = Math.min(n, step); - // PICK SAMPLE INDEXES - for (let i: number = 0; i < n; ++i) { - const idx: number = randint(0, remainders.length - 1); - advances.push(remainders.splice(idx, 1)[0]); - } - sort(advances.begin(), advances.end()); + // PICK SAMPLE INDEXES + for (let i: number = 0; i < n; ++i) { + const idx: number = randint(0, remainders.length - 1); + advances.push(remainders.splice(idx, 1)[0]); + } + sort(advances.begin(), advances.end()); - // CHANGE INDEXES TO ADVANCES - for (let i: number = n - 1; i >= 1; --i) - advances.set(i, advances.at(i) - advances.at(i - 1)); + // CHANGE INDEXES TO ADVANCES + for (let i: number = n - 1; i >= 1; --i) + advances.set(i, advances.at(i) - advances.at(i - 1)); - //---- - // FILL SAMPLES - //---- - for (const adv of advances) { - first = advance(first, adv); + //---- + // FILL SAMPLES + //---- + for (const adv of advances) { + first = advance(first, adv); - output.value = first.value; - output = output.next(); - } - return output; + output.value = first.value; + output = output.next(); + } + return output; } diff --git a/src/algorithm/sorting.ts b/src/algorithm/sorting.ts index 238d9f94..d82c256c 100644 --- a/src/algorithm/sorting.ts +++ b/src/algorithm/sorting.ts @@ -1,21 +1,20 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IForwardIterator } from "../iterator/IForwardIterator"; -import { IRandomAccessIterator } from "../iterator/IRandomAccessIterator"; -import { IPointer } from "../functional/IPointer"; -import { General } from "../internal/functional/General"; - import { Vector } from "../container/Vector"; +import { IPointer } from "../functional/IPointer"; import { less } from "../functional/comparators"; -import { iter_swap, copy } from "./modifiers"; -import { distance } from "../iterator/global"; - import { Comparator } from "../internal/functional/Comparator"; +import { General } from "../internal/functional/General"; import { Temporary } from "../internal/functional/Temporary"; +import { IForwardIterator } from "../iterator/IForwardIterator"; +import { IRandomAccessIterator } from "../iterator/IRandomAccessIterator"; +import { distance } from "../iterator/global"; +import { copy, iter_swap } from "./modifiers"; /* ========================================================= SORTINGS @@ -33,39 +32,37 @@ import { Temporary } from "../internal/functional/Temporary"; * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function sort< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - last: RandomAccessIterator, - comp: Comparator> = less, + first: RandomAccessIterator, + last: RandomAccessIterator, + comp: Comparator> = less, ): void { - const length: number = last.index() - first.index(); - if (length <= 0) return; + const length: number = last.index() - first.index(); + if (length <= 0) return; - const pivot_it: RandomAccessIterator = first.advance( - Math.floor(length / 2), - ); - const pivot: IPointer.ValueType = pivot_it.value; + const pivot_it: RandomAccessIterator = first.advance(Math.floor(length / 2)); + const pivot: IPointer.ValueType = pivot_it.value; - if (pivot_it.index() !== first.index()) iter_swap(first, pivot_it); + if (pivot_it.index() !== first.index()) iter_swap(first, pivot_it); - let i: number = 1; - for (let j: number = 1; j < length; ++j) { - const j_it: RandomAccessIterator = first.advance(j); - if (comp(j_it.value, pivot)) { - iter_swap(j_it, first.advance(i)); - ++i; - } + let i: number = 1; + for (let j: number = 1; j < length; ++j) { + const j_it: RandomAccessIterator = first.advance(j); + if (comp(j_it.value, pivot)) { + iter_swap(j_it, first.advance(i)); + ++i; } - iter_swap(first, first.advance(i - 1)); + } + iter_swap(first, first.advance(i - 1)); - sort(first, first.advance(i - 1), comp); - sort(first.advance(i), last, comp); + sort(first, first.advance(i - 1), comp); + sort(first.advance(i), last, comp); } /** @@ -76,24 +73,24 @@ export function sort< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function stable_sort< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - last: RandomAccessIterator, - comp: Comparator> = less, + first: RandomAccessIterator, + last: RandomAccessIterator, + comp: Comparator> = less, ): void { - const ramda = function ( - x: IPointer.ValueType, - y: IPointer.ValueType, - ): boolean { - return comp(x, y) && !comp(y, x); - }; - sort(first, last, ramda); + const ramda = function ( + x: IPointer.ValueType, + y: IPointer.ValueType, + ): boolean { + return comp(x, y) && !comp(y, x); + }; + sort(first, last, ramda); } /** @@ -105,26 +102,26 @@ export function stable_sort< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function partial_sort< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - middle: RandomAccessIterator, - last: RandomAccessIterator, - comp: Comparator> = less, + first: RandomAccessIterator, + middle: RandomAccessIterator, + last: RandomAccessIterator, + comp: Comparator> = less, ): void { - for (let i = first; !i.equals(middle); i = i.next()) { - let min: RandomAccessIterator = i; + for (let i = first; !i.equals(middle); i = i.next()) { + let min: RandomAccessIterator = i; - for (let j = i.next(); !j.equals(last); j = j.next()) - if (comp(j.value, min.value)) min = j; + for (let j = i.next(); !j.equals(last); j = j.next()) + if (comp(j.value, min.value)) min = j; - if (!i.equals(min)) iter_swap(i, min); - } + if (!i.equals(min)) iter_swap(i, min); + } } /** @@ -139,37 +136,37 @@ export function partial_sort< * @return Output Iterator of the last position by advancing. */ export function partial_sort_copy< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends General< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends General< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output_first: OutputIterator, - output_last: OutputIterator, - comp: Comparator> = less, + first: InputIterator, + last: InputIterator, + output_first: OutputIterator, + output_last: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - const input_size: number = distance(first, last); - const result_size: number = distance(output_first, output_last); + const input_size: number = distance(first, last); + const result_size: number = distance(output_first, output_last); - const vector: Vector> = new Vector( - first, - last, - ); - sort(vector.begin(), vector.end(), comp); + const vector: Vector> = new Vector( + first, + last, + ); + sort(vector.begin(), vector.end(), comp); - if (input_size > result_size) - output_first = copy( - vector.begin(), - vector.begin().advance(result_size), - output_first, - ); - else output_first = copy(vector.begin(), vector.end(), output_first); + if (input_size > result_size) + output_first = copy( + vector.begin(), + vector.begin().advance(result_size), + output_first, + ); + else output_first = copy(vector.begin(), vector.end(), output_first); - return output_first; + return output_first; } /** @@ -181,30 +178,30 @@ export function partial_sort_copy< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function nth_element< - RandomAccessIterator extends General< - IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - > - >, + RandomAccessIterator extends General< + IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + > + >, >( - first: RandomAccessIterator, - nth: RandomAccessIterator, - last: RandomAccessIterator, - comp: Comparator> = less, + first: RandomAccessIterator, + nth: RandomAccessIterator, + last: RandomAccessIterator, + comp: Comparator> = less, ): void { - const n: number = distance(first, nth); - for (let i = first; !i.equals(last); i = i.next()) { - let count: number = 0; - for (let j = first; !j.equals(last); j = j.next()) - if (i.equals(j)) continue; - else if (comp(i.value, j.value) && ++count > n) break; + const n: number = distance(first, nth); + for (let i = first; !i.equals(last); i = i.next()) { + let count: number = 0; + for (let j = first; !j.equals(last); j = j.next()) + if (i.equals(j)) continue; + else if (comp(i.value, j.value) && ++count > n) break; - if (count === n) { - iter_swap(nth, i); - return; - } + if (count === n) { + iter_swap(nth, i); + return; } + } } /* --------------------------------------------------------- @@ -220,15 +217,15 @@ export function nth_element< * @return Whether sorted or not. */ export function is_sorted< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - comp: Comparator> = less, + first: InputIterator, + last: InputIterator, + comp: Comparator> = less, ): boolean { - return is_sorted_until(first, last, comp).equals(last); + return is_sorted_until(first, last, comp).equals(last); } /** @@ -241,19 +238,19 @@ export function is_sorted< * @return Iterator to the first element who violates the order. */ export function is_sorted_until< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - comp: Comparator> = less, + first: InputIterator, + last: InputIterator, + comp: Comparator> = less, ): InputIterator { - if (first.equals(last)) return last; + if (first.equals(last)) return last; - for (let next = first.next(); !next.equals(last); next = next.next()) - if (comp(next.value, first.value)) return next; - else first = first.next(); + for (let next = first.next(); !next.equals(last); next = next.next()) + if (comp(next.value, first.value)) return next; + else first = first.next(); - return last; + return last; } diff --git a/src/base/container/Container.ts b/src/base/container/Container.ts index 02750306..fafbef33 100644 --- a/src/base/container/Container.ts +++ b/src/base/container/Container.ts @@ -1,13 +1,13 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { IContainer } from "./IContainer"; - -import { IForwardIterator } from "../../iterator/IForwardIterator"; import { ForOfAdaptor } from "../../internal/iterator/disposable/ForOfAdaptor"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; +import { IContainer } from "./IContainer"; /** * Basic container. @@ -21,126 +21,120 @@ import { ForOfAdaptor } from "../../internal/iterator/disposable/ForOfAdaptor"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class Container< - T extends PElem, - SourceT extends Container, - IteratorT extends IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - PElem - >, - ReverseT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - PElem - >, - PElem = T, + T extends PElem, + SourceT extends Container, + IteratorT extends IContainer.Iterator, + ReverseT extends IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + PElem + >, + PElem = T, > implements IContainer { - /* --------------------------------------------------------- + /* --------------------------------------------------------- ASSIGN & CLEAR --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract assign< - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void; - - /** - * @inheritDoc - */ - public abstract clear(): void; - - /* ========================================================= + /** + * @inheritDoc + */ + public abstract assign< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void; + + /** + * @inheritDoc + */ + public abstract clear(): void; + + /* ========================================================= ACCESSORS - SIZE - ITERATORS ============================================================ SIZE --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract size(): number; - - /** - * @inheritDoc - */ - public empty(): boolean { - return this.size() === 0; - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public abstract size(): number; + + /** + * @inheritDoc + */ + public empty(): boolean { + return this.size() === 0; + } + + /* --------------------------------------------------------- ITERATORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract begin(): IteratorT; - - /** - * @inheritDoc - */ - public abstract end(): IteratorT; - - /** - * @inheritDoc - */ - public rbegin(): ReverseT { - return this.end().reverse(); - } - - /** - * @inheritDoc - */ - public rend(): ReverseT { - return this.begin().reverse(); - } - - /** - * @inheritDoc - */ - public [Symbol.iterator](): IterableIterator { - return new ForOfAdaptor(this.begin(), this.end()); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public abstract begin(): IteratorT; + + /** + * @inheritDoc + */ + public abstract end(): IteratorT; + + /** + * @inheritDoc + */ + public rbegin(): ReverseT { + return this.end().reverse(); + } + + /** + * @inheritDoc + */ + public rend(): ReverseT { + return this.begin().reverse(); + } + + /** + * @inheritDoc + */ + public [Symbol.iterator](): IterableIterator { + return new ForOfAdaptor(this.begin(), this.end()); + } + + /* --------------------------------------------------------- ELEMENTS I/O --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract push(...items: PElem[]): number; - - /** - * @inheritDoc - */ - public abstract erase(pos: IteratorT): IteratorT; - - /** - * @inheritDoc - */ - public abstract erase(first: IteratorT, last: IteratorT): IteratorT; - - /* --------------------------------------------------------------- + /** + * @inheritDoc + */ + public abstract push(...items: PElem[]): number; + + /** + * @inheritDoc + */ + public abstract erase(pos: IteratorT): IteratorT; + + /** + * @inheritDoc + */ + public abstract erase(first: IteratorT, last: IteratorT): IteratorT; + + /* --------------------------------------------------------------- UTILITIES --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract swap(obj: SourceT): void; - - /** - * @inheritDoc - */ - public toJSON(): Array { - const ret: Array = []; - for (const elem of this) ret.push(elem); - - return ret; - } + /** + * @inheritDoc + */ + public abstract swap(obj: SourceT): void; + + /** + * @inheritDoc + */ + public toJSON(): Array { + const ret: Array = []; + for (const elem of this) ret.push(elem); + + return ret; + } } diff --git a/src/base/container/IArrayContainer.ts b/src/base/container/IArrayContainer.ts index f9af6a43..2516c8bf 100644 --- a/src/base/container/IArrayContainer.ts +++ b/src/base/container/IArrayContainer.ts @@ -1,11 +1,12 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { ILinearContainer } from "./ILinearContainer"; import { IRandomAccessIterator } from "../../iterator/IRandomAccessIterator"; +import { ILinearContainer } from "./ILinearContainer"; /** * Common interface for array containers. @@ -19,105 +20,99 @@ import { IRandomAccessIterator } from "../../iterator/IRandomAccessIterator"; * @author Jeongho Nam - https://github.com/samchon */ export interface IArrayContainer< - T extends PElem, - SourceT extends IArrayContainer, - IteratorT extends IArrayContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ReverseT extends IArrayContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - PElem = T, + T extends PElem, + SourceT extends IArrayContainer, + IteratorT extends IArrayContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ReverseT extends IArrayContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + PElem = T, > extends ILinearContainer { - /** - * Get iterator at specific position. - * - * @param index Specific position. - * @return The iterator at the *index*. - */ - nth(index: number): IteratorT; + /** + * Get iterator at specific position. + * + * @param index Specific position. + * @return The iterator at the *index*. + */ + nth(index: number): IteratorT; - /** - * Get element at specific position. - * - * @param index Specific position. - * @return The element at the *index*. - */ - at(index: number): T; + /** + * Get element at specific position. + * + * @param index Specific position. + * @return The element at the *index*. + */ + at(index: number): T; - /** - * Change element at specific position. - * - * @param index Specific position. - * @param val The new value to change. - */ - set(index: number, val: T): void; + /** + * Change element at specific position. + * + * @param index Specific position. + * @param val The new value to change. + */ + set(index: number, val: T): void; } export namespace IArrayContainer { - /** - * Iterator of {@link IArrayContainer} - * - * @author Jenogho Nam - */ - export type Iterator< - T extends ElemT, - SourceT extends IArrayContainer, - IteratorT extends IArrayContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ReverseT extends IArrayContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ElemT = T, - > = ILinearContainer.Iterator & - IRandomAccessIterator; + /** + * Iterator of {@link IArrayContainer} + * + * @author Jenogho Nam + */ + export type Iterator< + T extends ElemT, + SourceT extends IArrayContainer, + IteratorT extends IArrayContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ReverseT extends IArrayContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ElemT = T, + > = ILinearContainer.Iterator & + IRandomAccessIterator; - /** - * Reverse iterator of {@link IArrayContainer} - * - * @author Jeongho Nam - https://github.com/samchon - */ - export type ReverseIterator< - T extends ElemT, - SourceT extends IArrayContainer, - IteratorT extends IArrayContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ReverseT extends IArrayContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ElemT = T, - > = ILinearContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - ElemT - > & - IRandomAccessIterator; + /** + * Reverse iterator of {@link IArrayContainer} + * + * @author Jeongho Nam - https://github.com/samchon + */ + export type ReverseIterator< + T extends ElemT, + SourceT extends IArrayContainer, + IteratorT extends IArrayContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ReverseT extends IArrayContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ElemT = T, + > = ILinearContainer.ReverseIterator & + IRandomAccessIterator; } diff --git a/src/base/container/IContainer.ts b/src/base/container/IContainer.ts index b0cee35a..eb8c3844 100644 --- a/src/base/container/IContainer.ts +++ b/src/base/container/IContainer.ts @@ -1,17 +1,17 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { IBidirectionalContainer } from "../../ranges/container/IBidirectionalContainer"; import { IEmpty } from "../../internal/container/partial/IEmpty"; -import { ISize } from "../../internal/container/partial/ISize"; import { IPush } from "../../internal/container/partial/IPush"; - +import { ISize } from "../../internal/container/partial/ISize"; import { IForwardIterator } from "../../iterator/IForwardIterator"; -import { IReverseIterator } from "../../iterator/IReverseIterator"; import { IReversableIterator } from "../../iterator/IReversableIterator"; +import { IReverseIterator } from "../../iterator/IReverseIterator"; +import { IBidirectionalContainer } from "../../ranges/container/IBidirectionalContainer"; /** * Common interface for containers. @@ -25,198 +25,180 @@ import { IReversableIterator } from "../../iterator/IReversableIterator"; * @author Jeongho Nam - https://github.com/samchon */ export interface IContainer< - T extends PElem, - SourceT extends IContainer, - IteratorT extends IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - PElem - >, - ReverseT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - PElem - >, - PElem = T, + T extends PElem, + SourceT extends IContainer, + IteratorT extends IContainer.Iterator, + ReverseT extends IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + PElem + >, + PElem = T, > extends IBidirectionalContainer< - IContainer.Iterator, - ReverseT - >, - Iterable, - IEmpty, - ISize, - IPush { - /* --------------------------------------------------------- + IContainer.Iterator, + ReverseT + >, + Iterable, + IEmpty, + ISize, + IPush { + /* --------------------------------------------------------- ASSIGN & CLEAR --------------------------------------------------------- */ - /** - * Range Assigner. - * - * @param first Input iteartor of the first position. - * @param last Input iterator of the last position. - */ - assign< - InputIterator extends Readonly>, - >( - first: InputIterator, - last: InputIterator, - ): void; - - /** - * @inheritDoc - */ - clear(): void; - - /* ========================================================= + /** + * Range Assigner. + * + * @param first Input iteartor of the first position. + * @param last Input iterator of the last position. + */ + assign< + InputIterator extends Readonly>, + >( + first: InputIterator, + last: InputIterator, + ): void; + + /** + * @inheritDoc + */ + clear(): void; + + /* ========================================================= ACCESSORS - SIZE - ITERATORS ============================================================ SIZE --------------------------------------------------------- */ - /** - * @inheritDoc - */ - size(): number; + /** + * @inheritDoc + */ + size(): number; - /** - * @inheritDoc - */ - empty(): boolean; + /** + * @inheritDoc + */ + empty(): boolean; - /* --------------------------------------------------------- + /* --------------------------------------------------------- ITERATORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - begin(): IteratorT; - - /** - * @inheritDoc - */ - end(): IteratorT; - - /** - * @inheritDoc - */ - rbegin(): ReverseT; - - /** - * @inheritDoc - */ - rend(): ReverseT; - - /** - * @inheritDoc - */ - [Symbol.iterator](): IterableIterator; - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + begin(): IteratorT; + + /** + * @inheritDoc + */ + end(): IteratorT; + + /** + * @inheritDoc + */ + rbegin(): ReverseT; + + /** + * @inheritDoc + */ + rend(): ReverseT; + + /** + * @inheritDoc + */ + [Symbol.iterator](): IterableIterator; + + /* --------------------------------------------------------- ELEMENTS I/O --------------------------------------------------------- */ - push(...items: PElem[]): number; - - /** - * Erase an element. - * - * @param pos Position to erase. - * @return Iterator following the *pos*, strained by the erasing. - */ - erase(pos: IteratorT): IteratorT; - - /** - * Erase elements in range. - * - * @param first Range of the first position to erase. - * @param last Rangee of the last position to erase. - * @return Iterator following the last removed element, strained by the erasing. - */ - erase(first: IteratorT, last: IteratorT): IteratorT; - - /* --------------------------------------------------------------- + push(...items: PElem[]): number; + + /** + * Erase an element. + * + * @param pos Position to erase. + * @return Iterator following the *pos*, strained by the erasing. + */ + erase(pos: IteratorT): IteratorT; + + /** + * Erase elements in range. + * + * @param first Range of the first position to erase. + * @param last Rangee of the last position to erase. + * @return Iterator following the last removed element, strained by the erasing. + */ + erase(first: IteratorT, last: IteratorT): IteratorT; + + /* --------------------------------------------------------------- UTILITIES --------------------------------------------------------------- */ - /** - * Swap elements. - * - * @param obj Target container to swap. - */ - swap(obj: SourceT): void; - - /** - * Native function for `JSON.stringify()`. - * - * @return An array containing children elements. - */ - toJSON(): Array; + /** + * Swap elements. + * + * @param obj Target container to swap. + */ + swap(obj: SourceT): void; + + /** + * Native function for `JSON.stringify()`. + * + * @return An array containing children elements. + */ + toJSON(): Array; } export namespace IContainer { + /** + * Iterator of {@link IContainer}. + * + * @author Jeongho Nam - https://github.com/samchon + */ + export interface Iterator< + T extends Elem, + SourceT extends IContainer, + IteratorT extends Iterator, + ReverseIteratorT extends ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + Elem = T, + > extends Readonly> { /** - * Iterator of {@link IContainer}. + * Get source container. * - * @author Jeongho Nam - https://github.com/samchon + * @return The source container. */ - export interface Iterator< - T extends Elem, - SourceT extends IContainer< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - IteratorT extends Iterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - ReverseIteratorT extends ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - Elem = T, - > extends Readonly> { - /** - * Get source container. - * - * @return The source container. - */ - source(): SourceT; - - /** - * @inheritDoc - */ - reverse(): ReverseIteratorT; - } + source(): SourceT; /** - * Reverse iterator of {@link IContainer} + * @inheritDoc + */ + reverse(): ReverseIteratorT; + } + + /** + * Reverse iterator of {@link IContainer} + * + * @author Jeongho Nam - https://github.com/samchon + */ + export interface ReverseIterator< + T extends Elem, + Source extends IContainer, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + Elem = T, + > extends Readonly> { + /** + * Get source container. * - * @author Jeongho Nam - https://github.com/samchon + * @return The source container. */ - export interface ReverseIterator< - T extends Elem, - Source extends IContainer, - IteratorT extends Iterator, - ReverseT extends ReverseIterator, - Elem = T, - > extends Readonly> { - /** - * Get source container. - * - * @return The source container. - */ - source(): Source; - } + source(): Source; + } } diff --git a/src/base/container/IDequeContainer.ts b/src/base/container/IDequeContainer.ts index 89f0e9e2..caf1423c 100644 --- a/src/base/container/IDequeContainer.ts +++ b/src/base/container/IDequeContainer.ts @@ -1,11 +1,12 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { IContainer } from "./IContainer"; import { IDeque } from "../../internal/container/partial/IDeque"; +import { IContainer } from "./IContainer"; import { ILinearContainer } from "./ILinearContainer"; /** @@ -20,80 +21,68 @@ import { ILinearContainer } from "./ILinearContainer"; * @author Jeongho Nam - https://github.com/samchon */ export interface IDequeContainer< - T extends PElem, - SourceT extends IDequeContainer, - IteratorT extends IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - PElem - >, - ReverseT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - PElem - >, - PElem = T, + T extends PElem, + SourceT extends IDequeContainer, + IteratorT extends IContainer.Iterator, + ReverseT extends IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + PElem + >, + PElem = T, > extends IDeque, - ILinearContainer {} + ILinearContainer {} export namespace IDequeContainer { - /** - * Iterator of {@link IDequeContainer}. - * - * @author Jeongho Nam - https://github.com/samchon - */ - export type Iterator< - T extends ElemT, - SourceT extends IDequeContainer, - IteratorT extends IDequeContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ReverseT extends IDequeContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ElemT = T, - > = ILinearContainer.Iterator; + /** + * Iterator of {@link IDequeContainer}. + * + * @author Jeongho Nam - https://github.com/samchon + */ + export type Iterator< + T extends ElemT, + SourceT extends IDequeContainer, + IteratorT extends IDequeContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ReverseT extends IDequeContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ElemT = T, + > = ILinearContainer.Iterator; - /** - * Reverse iterator of {@link IDequeContainer}. - * - * @author Jeongho Nam - https://github.com/samchon - */ - export type ReverseIterator< - T extends ElemT, - SourceT extends IDequeContainer, - IteratorT extends IDequeContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ReverseT extends IDequeContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ElemT = T, - > = ILinearContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - ElemT - >; + /** + * Reverse iterator of {@link IDequeContainer}. + * + * @author Jeongho Nam - https://github.com/samchon + */ + export type ReverseIterator< + T extends ElemT, + SourceT extends IDequeContainer, + IteratorT extends IDequeContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ReverseT extends IDequeContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ElemT = T, + > = ILinearContainer.ReverseIterator; } diff --git a/src/base/container/IHashMap.ts b/src/base/container/IHashMap.ts index 77785de1..9b3a06d2 100644 --- a/src/base/container/IHashMap.ts +++ b/src/base/container/IHashMap.ts @@ -1,15 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { MapContainer } from "./MapContainer"; import { IHashContainer } from "../../internal/container/associative/IHashContainer"; - -import { IPair } from "../../utility/IPair"; -import { Entry } from "../../utility/Entry"; import { MapElementList } from "../../internal/container/associative/MapElementList"; +import { Entry } from "../../utility/Entry"; +import { IPair } from "../../utility/IPair"; +import { MapContainer } from "./MapContainer"; /** * Common interface for hash maps. @@ -22,78 +22,78 @@ import { MapElementList } from "../../internal/container/associative/MapElementL * @author Jeongho Nam - https://github.com/samchon */ export interface IHashMap< - Key, - T, - Unique extends boolean, - Source extends IHashMap, + Key, + T, + Unique extends boolean, + Source extends IHashMap, > extends MapContainer< - Key, - T, - Unique, - Source, - IHashMap.Iterator, - IHashMap.ReverseIterator - >, - IHashContainer< - Key, - Entry, - Source, - IHashMap.Iterator, - IHashMap.ReverseIterator, - IPair - > { - /* --------------------------------------------------------- + Key, + T, + Unique, + Source, + IHashMap.Iterator, + IHashMap.ReverseIterator + >, + IHashContainer< + Key, + Entry, + Source, + IHashMap.Iterator, + IHashMap.ReverseIterator, + IPair + > { + /* --------------------------------------------------------- ITERATORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - begin(): IHashMap.Iterator; + /** + * @inheritDoc + */ + begin(): IHashMap.Iterator; - /** - * Iterator to the first element in a specific bucket. - * - * @param index Index number of the specific bucket. - * @return Iterator from the specific bucket. - */ - begin(index: number): IHashMap.Iterator; + /** + * Iterator to the first element in a specific bucket. + * + * @param index Index number of the specific bucket. + * @return Iterator from the specific bucket. + */ + begin(index: number): IHashMap.Iterator; - /** - * @inheritDoc - */ - end(): IHashMap.Iterator; + /** + * @inheritDoc + */ + end(): IHashMap.Iterator; - /** - * Iterator to the end in a specific bucket. - * - * @param index Index number of the specific bucket. - * @return Iterator from the specific bucket. - */ - end(index: number): IHashMap.Iterator; + /** + * Iterator to the end in a specific bucket. + * + * @param index Index number of the specific bucket. + * @return Iterator from the specific bucket. + */ + end(index: number): IHashMap.Iterator; } export namespace IHashMap { - /** - * Iterator of {@link IHashMap} - * - * @author Jenogho Nam - */ - export type Iterator< - Key, - T, - Unique extends boolean, - Source extends IHashMap, - > = MapElementList.Iterator; + /** + * Iterator of {@link IHashMap} + * + * @author Jenogho Nam + */ + export type Iterator< + Key, + T, + Unique extends boolean, + Source extends IHashMap, + > = MapElementList.Iterator; - /** - * Reverse iterator of {@link IHashMap} - * - * @author Jenogho Nam - */ - export type ReverseIterator< - Key, - T, - Unique extends boolean, - Source extends IHashMap, - > = MapElementList.ReverseIterator; + /** + * Reverse iterator of {@link IHashMap} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + Key, + T, + Unique extends boolean, + Source extends IHashMap, + > = MapElementList.ReverseIterator; } diff --git a/src/base/container/IHashSet.ts b/src/base/container/IHashSet.ts index 0fcfc670..cc5b2b1c 100644 --- a/src/base/container/IHashSet.ts +++ b/src/base/container/IHashSet.ts @@ -1,12 +1,13 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { SetContainer } from "./SetContainer"; import { IHashContainer } from "../../internal/container/associative/IHashContainer"; import { SetElementList } from "../../internal/container/associative/SetElementList"; +import { SetContainer } from "./SetContainer"; /** * Common interface for hash sets. @@ -18,74 +19,74 @@ import { SetElementList } from "../../internal/container/associative/SetElementL * @author Jeongho Nam - https://github.com/samchon */ export interface IHashSet< - Key, - Unique extends boolean, - Source extends IHashSet, + Key, + Unique extends boolean, + Source extends IHashSet, > extends SetContainer< - Key, - Unique, - Source, - IHashSet.Iterator, - IHashSet.ReverseIterator - >, - IHashContainer< - Key, - Key, - Source, - IHashSet.Iterator, - IHashSet.ReverseIterator, - Key - > { - /* --------------------------------------------------------- + Key, + Unique, + Source, + IHashSet.Iterator, + IHashSet.ReverseIterator + >, + IHashContainer< + Key, + Key, + Source, + IHashSet.Iterator, + IHashSet.ReverseIterator, + Key + > { + /* --------------------------------------------------------- ITERATORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - begin(): IHashSet.Iterator; + /** + * @inheritDoc + */ + begin(): IHashSet.Iterator; - /** - * Iterator to the first element in a specific bucket. - * - * @param index Index number of the specific bucket. - * @return Iterator from the specific bucket. - */ - begin(index: number): IHashSet.Iterator; + /** + * Iterator to the first element in a specific bucket. + * + * @param index Index number of the specific bucket. + * @return Iterator from the specific bucket. + */ + begin(index: number): IHashSet.Iterator; - /** - * @inheritDoc - */ - end(): IHashSet.Iterator; + /** + * @inheritDoc + */ + end(): IHashSet.Iterator; - /** - * Iterator to the end in a specific bucket. - * - * @param index Index number of the specific bucket. - * @return Iterator from the specific bucket. - */ - end(index: number): IHashSet.Iterator; + /** + * Iterator to the end in a specific bucket. + * + * @param index Index number of the specific bucket. + * @return Iterator from the specific bucket. + */ + end(index: number): IHashSet.Iterator; } export namespace IHashSet { - /** - * Iterator of {@link IHashSet} - * - * @author Jenogho Nam - */ - export type Iterator< - Key, - Unique extends boolean, - Source extends IHashSet, - > = SetElementList.Iterator; + /** + * Iterator of {@link IHashSet} + * + * @author Jenogho Nam + */ + export type Iterator< + Key, + Unique extends boolean, + Source extends IHashSet, + > = SetElementList.Iterator; - /** - * Reverse iterator of {@link IHashSet} - * - * @author Jenogho Nam - */ - export type ReverseIterator< - Key, - Unique extends boolean, - Source extends IHashSet, - > = SetElementList.ReverseIterator; + /** + * Reverse iterator of {@link IHashSet} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + Key, + Unique extends boolean, + Source extends IHashSet, + > = SetElementList.ReverseIterator; } diff --git a/src/base/container/ILinearContainer.ts b/src/base/container/ILinearContainer.ts index 5eac8e76..aabdf6f6 100644 --- a/src/base/container/ILinearContainer.ts +++ b/src/base/container/ILinearContainer.ts @@ -1,15 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { IContainer } from "./IContainer"; import { ILinearContainerBase } from "../../internal/container/linear/ILinearContainerBase"; import { IFront } from "../../internal/container/partial/IFront"; import { IPushBack } from "../../internal/container/partial/IPushBack"; - import { IForwardIterator } from "../../iterator/IForwardIterator"; +import { IContainer } from "./IContainer"; /** * Common interface for linear containers. @@ -23,167 +23,167 @@ import { IForwardIterator } from "../../iterator/IForwardIterator"; * @author Jeongho Nam - https://github.com/samchon */ export interface ILinearContainer< - T extends PElem, - SourceT extends ILinearContainer, - IteratorT extends ILinearContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ReverseT extends ILinearContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - PElem = T, + T extends PElem, + SourceT extends ILinearContainer, + IteratorT extends ILinearContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ReverseT extends ILinearContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + PElem = T, > extends ILinearContainerBase, - IFront, - IPushBack { - /* --------------------------------------------------------- + IFront, + IPushBack { + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Fill Assigner. - * - * @param n Initial size. - * @param val Value to fill. - */ - assign(n: number, val: T): void; + /** + * Fill Assigner. + * + * @param n Initial size. + * @param val Value to fill. + */ + assign(n: number, val: T): void; - /** - * Range Assigner. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - */ - assign>>( - first: InputIterator, - last: InputIterator, - ): void; + /** + * Range Assigner. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + */ + assign>>( + first: InputIterator, + last: InputIterator, + ): void; - /** - * Resize this {@link Vector} forcibly. - * - * @param n New container size. - */ - resize(n: number): void; + /** + * Resize this {@link Vector} forcibly. + * + * @param n New container size. + */ + resize(n: number): void; - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * Get the last element. - * - * @return The last element. - */ - back(): T; + /** + * Get the last element. + * + * @return The last element. + */ + back(): T; - /** - * Change the last element. - * - * @param val The value to change. - */ - back(val: T): void; + /** + * Change the last element. + * + * @param val The value to change. + */ + back(val: T): void; - /* --------------------------------------------------------- + /* --------------------------------------------------------- ELEMENTS I/O --------------------------------------------------------- */ - /** - * @inheritDoc - */ - push_back(val: T): void; + /** + * @inheritDoc + */ + push_back(val: T): void; - /** - * Erase the last element. - */ - pop_back(): void; + /** + * Erase the last element. + */ + pop_back(): void; - /** - * Insert a single element. - * - * @param pos Position to insert. - * @param val Value to insert. - * @return An iterator to the newly inserted element. - */ - insert(pos: IteratorT, val: T): IteratorT; + /** + * Insert a single element. + * + * @param pos Position to insert. + * @param val Value to insert. + * @return An iterator to the newly inserted element. + */ + insert(pos: IteratorT, val: T): IteratorT; - /** - * Insert repeated elements. - * - * @param pos Position to insert. - * @param n Number of elements to insert. - * @param val Value to insert repeatedly. - * @return An iterator to the first of the newly inserted elements. - */ - insert(pos: IteratorT, n: number, val: T): IteratorT; + /** + * Insert repeated elements. + * + * @param pos Position to insert. + * @param n Number of elements to insert. + * @param val Value to insert repeatedly. + * @return An iterator to the first of the newly inserted elements. + */ + insert(pos: IteratorT, n: number, val: T): IteratorT; - /** - * Insert range elements. - * - * @param pos Position to insert. - * @param first Input iterator of the first position. - * @param last Input iteartor of the last position. - * @return An iterator to the first of the newly inserted elements. - */ - insert>>( - pos: IteratorT, - first: InputIterator, - last: InputIterator, - ): IteratorT; + /** + * Insert range elements. + * + * @param pos Position to insert. + * @param first Input iterator of the first position. + * @param last Input iteartor of the last position. + * @return An iterator to the first of the newly inserted elements. + */ + insert>>( + pos: IteratorT, + first: InputIterator, + last: InputIterator, + ): IteratorT; } export namespace ILinearContainer { - /** - * Iterator of {@link ILinearContainer} - * - * @author Jenogho Nam - */ - export type Iterator< - T extends ElemT, - SourceT extends ILinearContainer, - IteratorT extends ILinearContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ReverseT extends ILinearContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ElemT = T, - > = IContainer.Iterator; + /** + * Iterator of {@link ILinearContainer} + * + * @author Jenogho Nam + */ + export type Iterator< + T extends ElemT, + SourceT extends ILinearContainer, + IteratorT extends ILinearContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ReverseT extends ILinearContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ElemT = T, + > = IContainer.Iterator; - /** - * Reverse iterator of {@link ILinearContainer} - * - * @author Jenogho Nam - */ - export type ReverseIterator< - T extends ElemT, - SourceT extends ILinearContainer, - IteratorT extends ILinearContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ReverseT extends ILinearContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ElemT = T, - > = IContainer.ReverseIterator; + /** + * Reverse iterator of {@link ILinearContainer} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + T extends ElemT, + SourceT extends ILinearContainer, + IteratorT extends ILinearContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ReverseT extends ILinearContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ElemT = T, + > = IContainer.ReverseIterator; } diff --git a/src/base/container/ITreeMap.ts b/src/base/container/ITreeMap.ts index 079fb1cf..a3cea9b2 100644 --- a/src/base/container/ITreeMap.ts +++ b/src/base/container/ITreeMap.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { MapContainer } from "./MapContainer"; import { ITreeContainer } from "../../internal/container/associative/ITreeContainer"; - -import { IPair } from "../../utility/IPair"; import { Entry } from "../../utility/Entry"; +import { IPair } from "../../utility/IPair"; +import { MapContainer } from "./MapContainer"; /** * Common interface for tree maps. @@ -23,83 +23,76 @@ import { Entry } from "../../utility/Entry"; * @author Jeongho Nam - https://github.com/samchon */ export interface ITreeMap< + Key, + T, + Unique extends boolean, + Source extends ITreeMap, + IteratorT extends ITreeMap.Iterator< Key, T, - Unique extends boolean, - Source extends ITreeMap, - IteratorT extends ITreeMap.Iterator< - Key, - T, - Unique, - Source, - IteratorT, - ReverseT - >, - ReverseT extends ITreeMap.ReverseIterator< - Key, - T, - Unique, - Source, - IteratorT, - ReverseT - >, + Unique, + Source, + IteratorT, + ReverseT + >, + ReverseT extends ITreeMap.ReverseIterator< + Key, + T, + Unique, + Source, + IteratorT, + ReverseT + >, > extends MapContainer, - ITreeContainer< - Key, - Entry, - Source, - IteratorT, - ReverseT, - IPair - > {} + ITreeContainer< + Key, + Entry, + Source, + IteratorT, + ReverseT, + IPair + > {} export namespace ITreeMap { - /** - * Iterator of {@link ITreeMap} - * - * @author Jenogho Nam - */ - export type Iterator< - Key, - T, - Unique extends boolean, - Source extends ITreeMap, - IteratorT extends Iterator, - ReverseT extends ReverseIterator< - Key, - T, - Unique, - Source, - IteratorT, - ReverseT - >, - > = MapContainer.Iterator; + /** + * Iterator of {@link ITreeMap} + * + * @author Jenogho Nam + */ + export type Iterator< + Key, + T, + Unique extends boolean, + Source extends ITreeMap, + IteratorT extends Iterator, + ReverseT extends ReverseIterator< + Key, + T, + Unique, + Source, + IteratorT, + ReverseT + >, + > = MapContainer.Iterator; - /** - * Reverse iterator of {@link ITreeMap} - * - * @author Jenogho Nam - */ - export type ReverseIterator< - Key, - T, - Unique extends boolean, - Source extends ITreeMap, - IteratorT extends Iterator, - ReverseT extends ReverseIterator< - Key, - T, - Unique, - Source, - IteratorT, - ReverseT - >, - > = MapContainer.ReverseIterator< - Key, - T, - Unique, - Source, - IteratorT, - ReverseT - >; + /** + * Reverse iterator of {@link ITreeMap} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + Key, + T, + Unique extends boolean, + Source extends ITreeMap, + IteratorT extends Iterator, + ReverseT extends ReverseIterator< + Key, + T, + Unique, + Source, + IteratorT, + ReverseT + >, + > = MapContainer.ReverseIterator; } diff --git a/src/base/container/ITreeSet.ts b/src/base/container/ITreeSet.ts index bbc952f7..71679729 100644 --- a/src/base/container/ITreeSet.ts +++ b/src/base/container/ITreeSet.ts @@ -1,11 +1,12 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { SetContainer } from "./SetContainer"; import { ITreeContainer } from "../../internal/container/associative/ITreeContainer"; +import { SetContainer } from "./SetContainer"; /** * Common interface for tree sets. @@ -19,62 +20,44 @@ import { ITreeContainer } from "../../internal/container/associative/ITreeContai * @author Jeongho Nam - https://github.com/samchon */ export interface ITreeSet< + Key, + Unique extends boolean, + Source extends ITreeSet, + IteratorT extends ITreeSet.Iterator, + ReverseT extends ITreeSet.ReverseIterator< Key, - Unique extends boolean, - Source extends ITreeSet, - IteratorT extends ITreeSet.Iterator< - Key, - Unique, - Source, - IteratorT, - ReverseT - >, - ReverseT extends ITreeSet.ReverseIterator< - Key, - Unique, - Source, - IteratorT, - ReverseT - >, + Unique, + Source, + IteratorT, + ReverseT + >, > extends SetContainer, - ITreeContainer {} + ITreeContainer {} export namespace ITreeSet { - /** - * Iterator of {@link ITreeSet} - * - * @author Jenogho Nam - */ - export type Iterator< - Key, - Unique extends boolean, - SourceT extends ITreeSet, - IteratorT extends Iterator, - ReverseT extends ReverseIterator< - Key, - Unique, - SourceT, - IteratorT, - ReverseT - >, - > = SetContainer.Iterator; + /** + * Iterator of {@link ITreeSet} + * + * @author Jenogho Nam + */ + export type Iterator< + Key, + Unique extends boolean, + SourceT extends ITreeSet, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = SetContainer.Iterator; - /** - * Reverse iterator of {@link ITreeSet} - * - * @author Jenogho Nam - */ - export type ReverseIterator< - Key, - Unique extends boolean, - SourceT extends ITreeSet, - IteratorT extends Iterator, - ReverseT extends ReverseIterator< - Key, - Unique, - SourceT, - IteratorT, - ReverseT - >, - > = SetContainer.ReverseIterator; + /** + * Reverse iterator of {@link ITreeSet} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + Key, + Unique extends boolean, + SourceT extends ITreeSet, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = SetContainer.ReverseIterator; } diff --git a/src/base/container/MapContainer.ts b/src/base/container/MapContainer.ts index 2711295e..60953857 100644 --- a/src/base/container/MapContainer.ts +++ b/src/base/container/MapContainer.ts @@ -1,21 +1,20 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ import { IAssociativeContainer } from "../../internal/container/associative/IAssociativeContainer"; -import { IContainer } from "./IContainer"; -import { Container } from "./Container"; - -import { IForwardIterator } from "../../iterator/IForwardIterator"; import { ILinearContainerBase } from "../../internal/container/linear/ILinearContainerBase"; -import { IPair } from "../../utility/IPair"; +import { Temporary } from "../../internal/functional/Temporary"; import { NativeArrayIterator } from "../../internal/iterator/disposable/NativeArrayIterator"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; import { Entry } from "../../utility/Entry"; +import { IPair } from "../../utility/IPair"; import { Pair } from "../../utility/Pair"; - -import { Temporary } from "../../internal/functional/Temporary"; +import { Container } from "./Container"; +import { IContainer } from "./IContainer"; /** * Basic map container. @@ -30,137 +29,130 @@ import { Temporary } from "../../internal/functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class MapContainer< - Key, - T, - Unique extends boolean, - Source extends MapContainer< - Key, - T, - Unique, - Source, - IteratorT, - ReverseT - >, - IteratorT extends MapContainer.Iterator< - Key, - T, - Unique, - Source, - IteratorT, - ReverseT - >, - ReverseT extends MapContainer.ReverseIterator< - Key, - T, - Unique, - Source, - IteratorT, - ReverseT - >, + Key, + T, + Unique extends boolean, + Source extends MapContainer, + IteratorT extends MapContainer.Iterator< + Key, + T, + Unique, + Source, + IteratorT, + ReverseT + >, + ReverseT extends MapContainer.ReverseIterator< + Key, + T, + Unique, + Source, + IteratorT, + ReverseT + >, + > + extends Container, Source, IteratorT, ReverseT, IPair> + implements + IAssociativeContainer< + Key, + Entry, + Source, + IteratorT, + ReverseT, + IPair > - extends Container, Source, IteratorT, ReverseT, IPair> - implements - IAssociativeContainer< - Key, - Entry, - Source, - IteratorT, - ReverseT, - IPair - > { - protected data_: ILinearContainerBase< - Entry, - Source, - IteratorT, - ReverseT - >; - - /* --------------------------------------------------------- + protected data_: ILinearContainerBase< + Entry, + Source, + IteratorT, + ReverseT + >; + + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - protected constructor( - factory: ( - thisArg: Source, - ) => ILinearContainerBase, Source, IteratorT, ReverseT>, - ) { - super(); - this.data_ = factory(this as Temporary); - } - - /** - * @inheritDoc - */ - public assign< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - >(first: InputIterator, last: InputIterator): void { - // INSERT - this.clear(); - this.insert(first, last); - } - - /** - * @inheritDoc - */ - public clear(): void { - // TO BE ABSTRACT - this.data_.clear(); - } - - /* ========================================================= + /** + * Default Constructor. + */ + protected constructor( + factory: ( + thisArg: Source, + ) => ILinearContainerBase, Source, IteratorT, ReverseT>, + ) { + super(); + this.data_ = factory(this as Temporary); + } + + /** + * @inheritDoc + */ + public assign< + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + >(first: InputIterator, last: InputIterator): void { + // INSERT + this.clear(); + this.insert(first, last); + } + + /** + * @inheritDoc + */ + public clear(): void { + // TO BE ABSTRACT + this.data_.clear(); + } + + /* ========================================================= ACCESSORS - ITERATORS - ELEMENTS ============================================================ ITERATOR --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract find(key: Key): IteratorT; - - /** - * @inheritDoc - */ - public begin(): IteratorT { - return this.data_.begin(); - } - - /** - * @inheritDoc - */ - public end(): IteratorT { - return this.data_.end(); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public abstract find(key: Key): IteratorT; + + /** + * @inheritDoc + */ + public begin(): IteratorT { + return this.data_.begin(); + } + + /** + * @inheritDoc + */ + public end(): IteratorT { + return this.data_.end(); + } + + /* --------------------------------------------------------- ELEMENTS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public has(key: Key): boolean { - return !this.find(key).equals(this.end()); - } - - /** - * @inheritDoc - */ - public abstract count(key: Key): number; - - /** - * @inheritDoc - */ - public size(): number { - return this.data_.size(); - } - - /* ========================================================= + /** + * @inheritDoc + */ + public has(key: Key): boolean { + return !this.find(key).equals(this.end()); + } + + /** + * @inheritDoc + */ + public abstract count(key: Key): number; + + /** + * @inheritDoc + */ + public size(): number { + return this.data_.size(); + } + + /* ========================================================= ELEMENTS I/O - INSERT - ERASE @@ -169,247 +161,211 @@ export abstract class MapContainer< ============================================================ INSERT --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public push(...items: IPair[]): number { - // INSERT BY RANGE - const first = new NativeArrayIterator(items, 0); - const last = new NativeArrayIterator(items, items.length); - - this.insert(first, last); - - // RETURN SIZE - return this.size(); - } - - public abstract emplace( - key: Key, - val: T, - ): MapContainer.InsertRet; - public abstract emplace_hint(hint: IteratorT, key: Key, val: T): IteratorT; - - public insert( - pair: IPair, - ): MapContainer.InsertRet; - public insert(hint: IteratorT, pair: IPair): IteratorT; - public insert< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - >(first: InputIterator, last: InputIterator): void; - - public insert(...args: any[]): any { - if (args.length === 1) - return this.emplace(args[0].first, args[0].second); - else if ( - args[0].next instanceof Function && - args[1].next instanceof Function - ) - return this._Insert_by_range(args[0], args[1]); - else return this.emplace_hint(args[0], args[1].first, args[1].second); - } - - protected abstract _Insert_by_range< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - >(first: InputIterator, last: InputIterator): void; - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public push(...items: IPair[]): number { + // INSERT BY RANGE + const first = new NativeArrayIterator(items, 0); + const last = new NativeArrayIterator(items, items.length); + + this.insert(first, last); + + // RETURN SIZE + return this.size(); + } + + public abstract emplace( + key: Key, + val: T, + ): MapContainer.InsertRet; + public abstract emplace_hint(hint: IteratorT, key: Key, val: T): IteratorT; + + public insert( + pair: IPair, + ): MapContainer.InsertRet; + public insert(hint: IteratorT, pair: IPair): IteratorT; + public insert< + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + >(first: InputIterator, last: InputIterator): void; + + public insert(...args: any[]): any { + if (args.length === 1) return this.emplace(args[0].first, args[0].second); + else if ( + args[0].next instanceof Function && + args[1].next instanceof Function + ) + return this._Insert_by_range(args[0], args[1]); + else return this.emplace_hint(args[0], args[1].first, args[1].second); + } + + protected abstract _Insert_by_range< + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + >(first: InputIterator, last: InputIterator): void; + + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public erase(key: Key): number; - - /** - * @inheritDoc - */ - public erase(it: IteratorT): IteratorT; - - /** - * @inheritDoc - */ - public erase(begin: IteratorT, end: IteratorT): IteratorT; - - public erase(...args: any[]): any { - if ( - args.length === 1 && - (args[0] instanceof this.end().constructor === false || - ((args[0] as IteratorT).source() as any) !== this) - ) - return this._Erase_by_key(args[0]); - else if (args.length === 1) return this._Erase_by_range(args[0]); - else return this._Erase_by_range(args[0], args[1]); - } - - protected abstract _Erase_by_key(key: Key): number; - - protected _Erase_by_range( - first: IteratorT, - last: IteratorT = first.next(), - ): IteratorT { - // ERASE - const it = this.data_.erase(first, last); - - // POST-PROCESS - this._Handle_erase(first, last); - - return it; - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public erase(key: Key): number; + + /** + * @inheritDoc + */ + public erase(it: IteratorT): IteratorT; + + /** + * @inheritDoc + */ + public erase(begin: IteratorT, end: IteratorT): IteratorT; + + public erase(...args: any[]): any { + if ( + args.length === 1 && + (args[0] instanceof this.end().constructor === false || + ((args[0] as IteratorT).source() as any) !== this) + ) + return this._Erase_by_key(args[0]); + else if (args.length === 1) return this._Erase_by_range(args[0]); + else return this._Erase_by_range(args[0], args[1]); + } + + protected abstract _Erase_by_key(key: Key): number; + + protected _Erase_by_range( + first: IteratorT, + last: IteratorT = first.next(), + ): IteratorT { + // ERASE + const it = this.data_.erase(first, last); + + // POST-PROCESS + this._Handle_erase(first, last); + + return it; + } + + /* --------------------------------------------------------- UTILITY --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract swap(obj: Source): void; - - /** - * Merge two containers. - * - * @param source Source container to transfer. - */ - public abstract merge(source: Source): void; - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public abstract swap(obj: Source): void; + + /** + * Merge two containers. + * + * @param source Source container to transfer. + */ + public abstract merge(source: Source): void; + + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected abstract _Handle_insert(first: IteratorT, last: IteratorT): void; + protected abstract _Handle_insert(first: IteratorT, last: IteratorT): void; - protected abstract _Handle_erase(first: IteratorT, last: IteratorT): void; + protected abstract _Handle_erase(first: IteratorT, last: IteratorT): void; } /** * */ export namespace MapContainer { - /** - * Return type of {@link MapContainer.insert} - */ - export type InsertRet< - Key, - T, - Unique extends boolean, - SourceT extends MapContainer< - Key, - T, - Unique, - SourceT, - IteratorT, - Reverse - >, - IteratorT extends Iterator, - Reverse extends ReverseIterator< - Key, - T, - Unique, - SourceT, - IteratorT, - Reverse - >, - > = Unique extends true ? Pair : IteratorT; + /** + * Return type of {@link MapContainer.insert} + */ + export type InsertRet< + Key, + T, + Unique extends boolean, + SourceT extends MapContainer, + IteratorT extends Iterator, + Reverse extends ReverseIterator< + Key, + T, + Unique, + SourceT, + IteratorT, + Reverse + >, + > = Unique extends true ? Pair : IteratorT; + + /** + * Iterator of {@link MapContainer} + * + * @author Jenogho Nam + */ + export type Iterator< + Key, + T, + Unique extends boolean, + SourceT extends MapContainer, + IteratorT extends Iterator, + ReverseT extends ReverseIterator< + Key, + T, + Unique, + SourceT, + IteratorT, + ReverseT + >, + > = IteratorBase & + Readonly< + IContainer.Iterator< + Entry, + SourceT, + IteratorT, + ReverseT, + IPair + > + >; + + /** + * Reverse iterator of {@link MapContainer} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + Key, + T, + Unique extends boolean, + SourceT extends MapContainer, + IteratorT extends Iterator, + ReverseT extends ReverseIterator< + Key, + T, + Unique, + SourceT, + IteratorT, + ReverseT + >, + > = IteratorBase & + Readonly< + IContainer.ReverseIterator< + Entry, + SourceT, + IteratorT, + ReverseT, + IPair + > + >; + interface IteratorBase { /** - * Iterator of {@link MapContainer} - * - * @author Jenogho Nam + * The first, key element. */ - export type Iterator< - Key, - T, - Unique extends boolean, - SourceT extends MapContainer< - Key, - T, - Unique, - SourceT, - IteratorT, - ReverseT - >, - IteratorT extends Iterator< - Key, - T, - Unique, - SourceT, - IteratorT, - ReverseT - >, - ReverseT extends ReverseIterator< - Key, - T, - Unique, - SourceT, - IteratorT, - ReverseT - >, - > = IteratorBase & - Readonly< - IContainer.Iterator< - Entry, - SourceT, - IteratorT, - ReverseT, - IPair - > - >; + readonly first: Key; /** - * Reverse iterator of {@link MapContainer} - * - * @author Jenogho Nam + * The second, stored element. */ - export type ReverseIterator< - Key, - T, - Unique extends boolean, - SourceT extends MapContainer< - Key, - T, - Unique, - SourceT, - IteratorT, - ReverseT - >, - IteratorT extends Iterator< - Key, - T, - Unique, - SourceT, - IteratorT, - ReverseT - >, - ReverseT extends ReverseIterator< - Key, - T, - Unique, - SourceT, - IteratorT, - ReverseT - >, - > = IteratorBase & - Readonly< - IContainer.ReverseIterator< - Entry, - SourceT, - IteratorT, - ReverseT, - IPair - > - >; - - interface IteratorBase { - /** - * The first, key element. - */ - readonly first: Key; - - /** - * The second, stored element. - */ - second: T; - } + second: T; + } } diff --git a/src/base/container/MultiMap.ts b/src/base/container/MultiMap.ts index fa4a1e8a..632c71ec 100644 --- a/src/base/container/MultiMap.ts +++ b/src/base/container/MultiMap.ts @@ -1,13 +1,13 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { MapContainer } from "./MapContainer"; - import { IForwardIterator } from "../../iterator/IForwardIterator"; import { IPair } from "../../utility/IPair"; +import { MapContainer } from "./MapContainer"; /** * Basic map container allowing duplicated keys. @@ -21,133 +21,126 @@ import { IPair } from "../../utility/IPair"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class MultiMap< - Key, - T, - Source extends MultiMap, - Iterator extends MultiMap.Iterator, - Reverse extends MultiMap.ReverseIterator, + Key, + T, + Source extends MultiMap, + Iterator extends MultiMap.Iterator, + Reverse extends MultiMap.ReverseIterator, > extends MapContainer { - /* --------------------------------------------------------- + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - /** - * Construct and insert an element. - * - * @param key Key to be mapped. - * @param value Value to emplace. - * @return An iterator to the newly inserted element. - */ - public abstract emplace(key: Key, value: T): Iterator; + /** + * Construct and insert an element. + * + * @param key Key to be mapped. + * @param value Value to emplace. + * @return An iterator to the newly inserted element. + */ + public abstract emplace(key: Key, value: T): Iterator; - /** - * Construct and insert element with hint. - * - * @param hint Hint for the position where the element can be inserted. - * @param key Key of the new element. - * @param val Value of the new element. - * @return An iterator to the newly inserted element. - */ - public abstract emplace_hint(hint: Iterator, key: Key, val: T): Iterator; + /** + * Construct and insert element with hint. + * + * @param hint Hint for the position where the element can be inserted. + * @param key Key of the new element. + * @param val Value of the new element. + * @return An iterator to the newly inserted element. + */ + public abstract emplace_hint(hint: Iterator, key: Key, val: T): Iterator; - /** - * Insert an element. - * - * @param pair A tuple to be referenced for the insert. - * @return An iterator to the newly inserted element. - */ - public insert(pair: IPair): Iterator; + /** + * Insert an element. + * + * @param pair A tuple to be referenced for the insert. + * @return An iterator to the newly inserted element. + */ + public insert(pair: IPair): Iterator; - /** - * Insert an element with hint. - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A tuple to be referenced for the insert. - * @return An iterator to the newly inserted element. - */ - public insert(hint: Iterator, pair: IPair): Iterator; + /** + * Insert an element with hint. + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A tuple to be referenced for the insert. + * @return An iterator to the newly inserted element. + */ + public insert(hint: Iterator, pair: IPair): Iterator; - /** - * Insert range elements. - * - * @param first Input iterator of the first position. - * @param last Input iteartor of the last position. - */ - public insert< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - >(first: InputIterator, last: InputIterator): void; + /** + * Insert range elements. + * + * @param first Input iterator of the first position. + * @param last Input iteartor of the last position. + */ + public insert< + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + >(first: InputIterator, last: InputIterator): void; - public insert(...args: any[]): any { - return (super.insert as Function)(...args); - } + public insert(...args: any[]): any { + return (super.insert as Function)(...args); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - protected abstract _Key_eq(x: Key, y: Key): boolean; + protected abstract _Key_eq(x: Key, y: Key): boolean; - protected _Erase_by_key(key: Key): number { - const first = this.find(key); - if (first.equals(this.end()) === true) return 0; + protected _Erase_by_key(key: Key): number { + const first = this.find(key); + if (first.equals(this.end()) === true) return 0; - let last = first.next(); - let ret: number = 1; + let last = first.next(); + let ret: number = 1; - while (!last.equals(this.end()) && this._Key_eq(key, last.first)) { - last = last.next(); - ++ret; - } - this._Erase_by_range(first, last); - return ret; + while (!last.equals(this.end()) && this._Key_eq(key, last.first)) { + last = last.next(); + ++ret; } + this._Erase_by_range(first, last); + return ret; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- UTILITY --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public merge(source: Source): void { - this.insert(source.begin(), source.end()); - source.clear(); - } + /** + * @inheritDoc + */ + public merge(source: Source): void { + this.insert(source.begin(), source.end()); + source.clear(); + } } /** * */ export namespace MultiMap { - /** - * Iterator of {@link MultiMap} - * - * @author Jenogho Nam - */ - export type Iterator< - Key, - T, - SourceT extends MultiMap, - IteratorT extends Iterator, - ReverseT extends ReverseIterator, - > = MapContainer.Iterator; + /** + * Iterator of {@link MultiMap} + * + * @author Jenogho Nam + */ + export type Iterator< + Key, + T, + SourceT extends MultiMap, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = MapContainer.Iterator; - /** - * Reverse iterator of {@link MultiMap} - * - * @author Jenogho Nam - */ - export type ReverseIterator< - Key, - T, - SourceT extends MultiMap, - IteratorT extends Iterator, - ReverseT extends ReverseIterator, - > = MapContainer.ReverseIterator< - Key, - T, - false, - SourceT, - IteratorT, - ReverseT - >; + /** + * Reverse iterator of {@link MultiMap} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + Key, + T, + SourceT extends MultiMap, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = MapContainer.ReverseIterator; } diff --git a/src/base/container/MultiSet.ts b/src/base/container/MultiSet.ts index f5431fb7..ef743e37 100644 --- a/src/base/container/MultiSet.ts +++ b/src/base/container/MultiSet.ts @@ -1,12 +1,12 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { SetContainer } from "./SetContainer"; - import { IForwardIterator } from "../../iterator/IForwardIterator"; +import { SetContainer } from "./SetContainer"; /** * Basic set container allowing multiple keys. @@ -20,102 +20,102 @@ import { IForwardIterator } from "../../iterator/IForwardIterator"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class MultiSet< - Key, - Source extends MultiSet, - IteratorT extends MultiSet.Iterator, - ReverseT extends MultiSet.ReverseIterator, + Key, + Source extends MultiSet, + IteratorT extends MultiSet.Iterator, + ReverseT extends MultiSet.ReverseIterator, > extends SetContainer { - /* --------------------------------------------------------- + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - /** - * Insert an element. - * - * @param pair A tuple to be referenced for the insert. - * @return An iterator to the newly inserted element. - */ - public insert(key: Key): IteratorT; + /** + * Insert an element. + * + * @param pair A tuple to be referenced for the insert. + * @return An iterator to the newly inserted element. + */ + public insert(key: Key): IteratorT; - /** - * Insert an element with hint. - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A tuple to be referenced for the insert. - * @return An iterator to the newly inserted element. - */ - public insert(hint: IteratorT, key: Key): IteratorT; + /** + * Insert an element with hint. + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A tuple to be referenced for the insert. + * @return An iterator to the newly inserted element. + */ + public insert(hint: IteratorT, key: Key): IteratorT; - /** - * Insert range elements. - * - * @param first Input iterator of the first position. - * @param last Input iteartor of the last position. - */ - public insert< - InputIterator extends Readonly>, - >(begin: InputIterator, end: InputIterator): void; + /** + * Insert range elements. + * + * @param first Input iterator of the first position. + * @param last Input iteartor of the last position. + */ + public insert< + InputIterator extends Readonly>, + >(begin: InputIterator, end: InputIterator): void; - public insert(...args: any[]): any { - return (super.insert as Function)(...args); - } + public insert(...args: any[]): any { + return (super.insert as Function)(...args); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - protected abstract _Key_eq(x: Key, y: Key): boolean; + protected abstract _Key_eq(x: Key, y: Key): boolean; - protected _Erase_by_val(key: Key): number { - const first = this.find(key); - if (first.equals(this.end()) === true) return 0; + protected _Erase_by_val(key: Key): number { + const first = this.find(key); + if (first.equals(this.end()) === true) return 0; - let last = first.next(); - let ret: number = 1; + let last = first.next(); + let ret: number = 1; - while (!last.equals(this.end()) && this._Key_eq(key, last.value)) { - last = last.next(); - ++ret; - } - this._Erase_by_range(first, last); - return ret; + while (!last.equals(this.end()) && this._Key_eq(key, last.value)) { + last = last.next(); + ++ret; } + this._Erase_by_range(first, last); + return ret; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- UTILITY --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public merge(source: Source): void { - this.insert(source.begin(), source.end()); - source.clear(); - } + /** + * @inheritDoc + */ + public merge(source: Source): void { + this.insert(source.begin(), source.end()); + source.clear(); + } } /** * */ export namespace MultiSet { - /** - * Iterator of {@link MultiSet} - * - * @author Jenogho Nam - */ - export type Iterator< - Key, - SourceT extends MultiSet, - IteratorT extends Iterator, - ReverseT extends ReverseIterator, - > = SetContainer.Iterator; + /** + * Iterator of {@link MultiSet} + * + * @author Jenogho Nam + */ + export type Iterator< + Key, + SourceT extends MultiSet, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = SetContainer.Iterator; - /** - * Reverse iterator of {@link MultiSet} - * - * @author Jenogho Nam - */ - export type ReverseIterator< - Key, - SourceT extends MultiSet, - IteratorT extends Iterator, - ReverseT extends ReverseIterator, - > = SetContainer.ReverseIterator; + /** + * Reverse iterator of {@link MultiSet} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + Key, + SourceT extends MultiSet, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = SetContainer.ReverseIterator; } diff --git a/src/base/container/SetContainer.ts b/src/base/container/SetContainer.ts index f6d0e81c..bb8d6a5a 100644 --- a/src/base/container/SetContainer.ts +++ b/src/base/container/SetContainer.ts @@ -1,19 +1,18 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ import { IAssociativeContainer } from "../../internal/container/associative/IAssociativeContainer"; -import { IContainer } from "./IContainer"; -import { Container } from "./Container"; - -import { IForwardIterator } from "../../iterator/IForwardIterator"; import { ILinearContainerBase } from "../../internal/container/linear/ILinearContainerBase"; +import { Temporary } from "../../internal/functional/Temporary"; import { NativeArrayIterator } from "../../internal/iterator/disposable/NativeArrayIterator"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; import { Pair } from "../../utility/Pair"; - -import { Temporary } from "../../internal/functional/Temporary"; +import { Container } from "./Container"; +import { IContainer } from "./IContainer"; /** * Basic set container. @@ -27,113 +26,112 @@ import { Temporary } from "../../internal/functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class SetContainer< - Key, - Unique extends boolean, - SourceT extends SetContainer, - IteratorT extends SetContainer.Iterator< - Key, - Unique, - SourceT, - IteratorT, - ReverseT - >, - ReverseT extends SetContainer.ReverseIterator< - Key, - Unique, - SourceT, - IteratorT, - ReverseT - >, - > - extends Container - implements - IAssociativeContainer + Key, + Unique extends boolean, + SourceT extends SetContainer, + IteratorT extends SetContainer.Iterator< + Key, + Unique, + SourceT, + IteratorT, + ReverseT + >, + ReverseT extends SetContainer.ReverseIterator< + Key, + Unique, + SourceT, + IteratorT, + ReverseT + >, + > + extends Container + implements IAssociativeContainer { - protected data_: ILinearContainerBase; + protected data_: ILinearContainerBase; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - protected constructor( - factory: ( - thisArg: SourceT, - ) => ILinearContainerBase, - ) { - super(); - this.data_ = factory(this); - } - - /** - * @inheritDoc - */ - public assign< - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void { - // INSERT - this.clear(); - this.insert(first, last); - } - - /** - * @inheritDoc - */ - public clear(): void { - // TO BE ABSTRACT - this.data_.clear(); - } - - /* ========================================================= + /** + * Default Constructor. + */ + protected constructor( + factory: ( + thisArg: SourceT, + ) => ILinearContainerBase, + ) { + super(); + this.data_ = factory(this); + } + + /** + * @inheritDoc + */ + public assign< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void { + // INSERT + this.clear(); + this.insert(first, last); + } + + /** + * @inheritDoc + */ + public clear(): void { + // TO BE ABSTRACT + this.data_.clear(); + } + + /* ========================================================= ACCESSORS - ITERATORS - ELEMENTS ============================================================ ITERATOR --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract find(key: Key): IteratorT; - - /** - * @inheritDoc - */ - public begin(): IteratorT { - return this.data_.begin(); - } - - /** - * @inheritDoc - */ - public end(): IteratorT { - return this.data_.end(); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public abstract find(key: Key): IteratorT; + + /** + * @inheritDoc + */ + public begin(): IteratorT { + return this.data_.begin(); + } + + /** + * @inheritDoc + */ + public end(): IteratorT { + return this.data_.end(); + } + + /* --------------------------------------------------------- ELEMENTS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public has(key: Key): boolean { - return !this.find(key).equals(this.end()); - } - - /** - * @inheritDoc - */ - public abstract count(key: Key): number; - - /** - * @inheritDoc - */ - public size(): number { - return this.data_.size(); - } - - /* ========================================================= + /** + * @inheritDoc + */ + public has(key: Key): boolean { + return !this.find(key).equals(this.end()); + } + + /** + * @inheritDoc + */ + public abstract count(key: Key): number; + + /** + * @inheritDoc + */ + public size(): number { + return this.data_.size(); + } + + /* ========================================================= ELEMENTS I/O - INSERT - ERASE @@ -142,179 +140,158 @@ export abstract class SetContainer< ============================================================ INSERT --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public push(...items: Key[]): number { - if (items.length === 0) return this.size(); - - // INSERT BY RANGE - const first: NativeArrayIterator = new NativeArrayIterator( - items, - 0, - ); - const last: NativeArrayIterator = new NativeArrayIterator( - items, - items.length, - ); - - this._Insert_by_range(first, last); - - // RETURN SIZE - return this.size(); - } - - public insert( - key: Key, - ): SetContainer.InsertRet; - public insert(hint: IteratorT, key: Key): IteratorT; - public insert< - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void; - - public insert(...args: any[]): any { - if (args.length === 1) return this._Insert_by_key(args[0]); - else if ( - args[0].next instanceof Function && - args[1].next instanceof Function - ) - return this._Insert_by_range(args[0], args[1]); - else return this._Insert_by_hint(args[0], args[1]); - } - - protected abstract _Insert_by_key( - key: Key, - ): SetContainer.InsertRet; - protected abstract _Insert_by_hint(hint: IteratorT, key: Key): IteratorT; - protected abstract _Insert_by_range< - InputIterator extends Readonly>, - >(begin: InputIterator, end: InputIterator): void; - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public push(...items: Key[]): number { + if (items.length === 0) return this.size(); + + // INSERT BY RANGE + const first: NativeArrayIterator = new NativeArrayIterator(items, 0); + const last: NativeArrayIterator = new NativeArrayIterator( + items, + items.length, + ); + + this._Insert_by_range(first, last); + + // RETURN SIZE + return this.size(); + } + + public insert( + key: Key, + ): SetContainer.InsertRet; + public insert(hint: IteratorT, key: Key): IteratorT; + public insert< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void; + + public insert(...args: any[]): any { + if (args.length === 1) return this._Insert_by_key(args[0]); + else if ( + args[0].next instanceof Function && + args[1].next instanceof Function + ) + return this._Insert_by_range(args[0], args[1]); + else return this._Insert_by_hint(args[0], args[1]); + } + + protected abstract _Insert_by_key( + key: Key, + ): SetContainer.InsertRet; + protected abstract _Insert_by_hint(hint: IteratorT, key: Key): IteratorT; + protected abstract _Insert_by_range< + InputIterator extends Readonly>, + >(begin: InputIterator, end: InputIterator): void; + + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public erase(key: Key): number; - - /** - * @inheritDoc - */ - public erase(pos: IteratorT): IteratorT; - - /** - * @inheritDoc - */ - public erase(first: IteratorT, last: IteratorT): IteratorT; - - public erase(...args: any[]): any { - if ( - args.length === 1 && - !( - args[0] instanceof this.end().constructor && - (args[0] as IteratorT).source() === this - ) - ) - return this._Erase_by_val(args[0]); - else if (args.length === 1) return this._Erase_by_range(args[0]); - else return this._Erase_by_range(args[0], args[1]); - } - - protected abstract _Erase_by_val(key: Key): number; - - protected _Erase_by_range( - first: IteratorT, - last: IteratorT = first.next(), - ): IteratorT { - // ERASE - const it = this.data_.erase(first, last); - - // POST-PROCESS - this._Handle_erase(first, last); - - return it; - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public erase(key: Key): number; + + /** + * @inheritDoc + */ + public erase(pos: IteratorT): IteratorT; + + /** + * @inheritDoc + */ + public erase(first: IteratorT, last: IteratorT): IteratorT; + + public erase(...args: any[]): any { + if ( + args.length === 1 && + !( + args[0] instanceof this.end().constructor && + (args[0] as IteratorT).source() === this + ) + ) + return this._Erase_by_val(args[0]); + else if (args.length === 1) return this._Erase_by_range(args[0]); + else return this._Erase_by_range(args[0], args[1]); + } + + protected abstract _Erase_by_val(key: Key): number; + + protected _Erase_by_range( + first: IteratorT, + last: IteratorT = first.next(), + ): IteratorT { + // ERASE + const it = this.data_.erase(first, last); + + // POST-PROCESS + this._Handle_erase(first, last); + + return it; + } + + /* --------------------------------------------------------- UTILITY --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract swap(obj: SourceT): void; + /** + * @inheritDoc + */ + public abstract swap(obj: SourceT): void; - /** - * @inheritDoc - */ - public abstract merge(source: SourceT): void; + /** + * @inheritDoc + */ + public abstract merge(source: SourceT): void; - /* --------------------------------------------------------- + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected abstract _Handle_insert(first: IteratorT, last: IteratorT): void; + protected abstract _Handle_insert(first: IteratorT, last: IteratorT): void; - protected abstract _Handle_erase(first: IteratorT, last: IteratorT): void; + protected abstract _Handle_erase(first: IteratorT, last: IteratorT): void; } /** * */ export namespace SetContainer { - /** - * Return type of {@link SetContainer.insert} - */ - export type InsertRet< - Key, - Unique extends boolean, - Source extends SetContainer, - IteratorT extends Iterator, - ReverseT extends ReverseIterator< - Key, - Unique, - Source, - IteratorT, - ReverseT - >, - > = Unique extends true ? Pair : IteratorT; - - /** - * Iterator of {@link SetContainer} - * - * @author Jenogho Nam - */ - export type Iterator< - Key, - Unique extends boolean, - SourceT extends SetContainer, - IteratorT extends Iterator, - ReverseT extends ReverseIterator< - Key, - Unique, - SourceT, - IteratorT, - ReverseT - >, - > = Readonly>; - - /** - * Reverse iterator of {@link SetContainer} - * - * @author Jenogho Nam - */ - export type ReverseIterator< - Key, - Unique extends boolean, - SourceT extends SetContainer, - IteratorT extends Iterator, - ReverseT extends ReverseIterator< - Key, - Unique, - SourceT, - IteratorT, - ReverseT - >, - > = Readonly< - IContainer.ReverseIterator - >; + /** + * Return type of {@link SetContainer.insert} + */ + export type InsertRet< + Key, + Unique extends boolean, + Source extends SetContainer, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = Unique extends true ? Pair : IteratorT; + + /** + * Iterator of {@link SetContainer} + * + * @author Jenogho Nam + */ + export type Iterator< + Key, + Unique extends boolean, + SourceT extends SetContainer, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = Readonly>; + + /** + * Reverse iterator of {@link SetContainer} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + Key, + Unique extends boolean, + SourceT extends SetContainer, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = Readonly< + IContainer.ReverseIterator + >; } diff --git a/src/base/container/UniqueMap.ts b/src/base/container/UniqueMap.ts index c6b134fd..475e0f06 100644 --- a/src/base/container/UniqueMap.ts +++ b/src/base/container/UniqueMap.ts @@ -1,17 +1,16 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { MapContainer } from "./MapContainer"; - +import { ErrorGenerator } from "../../internal/exception/ErrorGenerator"; import { IForwardIterator } from "../../iterator/IForwardIterator"; -import { IPair } from "../../utility/IPair"; import { Entry } from "../../utility/Entry"; +import { IPair } from "../../utility/IPair"; import { Pair } from "../../utility/Pair"; - -import { ErrorGenerator } from "../../internal/exception/ErrorGenerator"; +import { MapContainer } from "./MapContainer"; /** * Basic map container blocking duplicated key. @@ -25,284 +24,271 @@ import { ErrorGenerator } from "../../internal/exception/ErrorGenerator"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class UniqueMap< - Key, - T, - Source extends UniqueMap, - Iterator extends UniqueMap.Iterator, - Reverse extends UniqueMap.ReverseIterator< - Key, - T, - Source, - Iterator, - Reverse - >, + Key, + T, + Source extends UniqueMap, + Iterator extends UniqueMap.Iterator, + Reverse extends UniqueMap.ReverseIterator, > extends MapContainer { - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public count(key: Key): number { - return this.find(key).equals(this.end()) ? 0 : 1; - } - - /** - * Get a value. - * - * @param key Key to search for. - * @return The value mapped by the key. - */ - public get(key: Key): T { - const it = this.find(key); - if (it.equals(this.end()) === true) - throw ErrorGenerator.key_nout_found(this, "get", key); - - return it.second; - } - - /** - * Take a value. - * - * Get a value, or set the value and returns it. - * - * @param key Key to search for. - * @param generator Value generator when the matched key not found - * @returns Value, anyway - */ - public take(key: Key, generator: () => T): T { - const it = this.find(key); - return it.equals(this.end()) - ? this.emplace(key, generator()).first.second - : it.second; - } - - /** - * Set a value with key. - * - * @param key Key to be mapped or search for. - * @param val Value to insert or assign. - */ - public set(key: Key, val: T): void { - this.insert_or_assign(key, val); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public count(key: Key): number { + return this.find(key).equals(this.end()) ? 0 : 1; + } + + /** + * Get a value. + * + * @param key Key to search for. + * @return The value mapped by the key. + */ + public get(key: Key): T { + const it = this.find(key); + if (it.equals(this.end()) === true) + throw ErrorGenerator.key_nout_found(this, "get", key); + + return it.second; + } + + /** + * Take a value. + * + * Get a value, or set the value and returns it. + * + * @param key Key to search for. + * @param generator Value generator when the matched key not found + * @returns Value, anyway + */ + public take(key: Key, generator: () => T): T { + const it = this.find(key); + return it.equals(this.end()) + ? this.emplace(key, generator()).first.second + : it.second; + } + + /** + * Set a value with key. + * + * @param key Key to be mapped or search for. + * @param val Value to insert or assign. + */ + public set(key: Key, val: T): void { + this.insert_or_assign(key, val); + } + + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - /** - * Construct and insert element. - * - * @param key Key to be mapped or search for. - * @param value Value to emplace. - * @return {@link Pair} of an iterator to the newly inserted element and `true`, if the specified *key* doesn't exist, otherwise {@link Pair} of iterator to the ordinary element and `false`. - */ - public abstract emplace(key: Key, value: T): Pair; - - /** - * Construct and insert element with hint. - * - * @param hint Hint for the position where the element can be inserted. - * @param key Key of the new element. - * @param val Value of the new element. - * @return An iterator to the newly inserted element, if the specified key doesn't exist, otherwise an iterator to the ordinary element. - */ - public abstract emplace_hint(hint: Iterator, key: Key, val: T): Iterator; - - /** - * Insert an element. - * - * @param pair A tuple to be referenced for the insert. - * @return {@link Pair} of an iterator to the newly inserted element and `true`, if the specified *key* doesn't exist, otherwise {@link Pair} of iterator to the ordinary element and `false`. - */ - public insert(pair: IPair): Pair; - - /** - * Insert an element with hint. - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A tuple to be referenced for the insert. - * @return An iterator to the newly inserted element, if the specified key doesn't exist, otherwise an iterator to the ordinary element. - */ - public insert(hint: Iterator, pair: IPair): Iterator; - - /** - * Insert range elements. - * - * @param first Input iterator of the first position. - * @param last Input iteartor of the last position. - */ - public insert< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - >(first: InputIterator, last: InputIterator): void; - - public insert(...args: any[]): any { - return (super.insert as Function)(...args); - } + /** + * Construct and insert element. + * + * @param key Key to be mapped or search for. + * @param value Value to emplace. + * @return {@link Pair} of an iterator to the newly inserted element and `true`, if the specified *key* doesn't exist, otherwise {@link Pair} of iterator to the ordinary element and `false`. + */ + public abstract emplace(key: Key, value: T): Pair; + + /** + * Construct and insert element with hint. + * + * @param hint Hint for the position where the element can be inserted. + * @param key Key of the new element. + * @param val Value of the new element. + * @return An iterator to the newly inserted element, if the specified key doesn't exist, otherwise an iterator to the ordinary element. + */ + public abstract emplace_hint(hint: Iterator, key: Key, val: T): Iterator; + + /** + * Insert an element. + * + * @param pair A tuple to be referenced for the insert. + * @return {@link Pair} of an iterator to the newly inserted element and `true`, if the specified *key* doesn't exist, otherwise {@link Pair} of iterator to the ordinary element and `false`. + */ + public insert(pair: IPair): Pair; + + /** + * Insert an element with hint. + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A tuple to be referenced for the insert. + * @return An iterator to the newly inserted element, if the specified key doesn't exist, otherwise an iterator to the ordinary element. + */ + public insert(hint: Iterator, pair: IPair): Iterator; + + /** + * Insert range elements. + * + * @param first Input iterator of the first position. + * @param last Input iteartor of the last position. + */ + public insert< + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + >(first: InputIterator, last: InputIterator): void; - protected _Insert_by_range< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - >(first: InputIterator, last: InputIterator): void { - for (let it = first; !it.equals(last); it = it.next()) - this.emplace(it.value.first, it.value.second); - } + public insert(...args: any[]): any { + return (super.insert as Function)(...args); + } + + protected _Insert_by_range< + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + >(first: InputIterator, last: InputIterator): void { + for (let it = first; !it.equals(last); it = it.next()) + this.emplace(it.value.first, it.value.second); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ASSIGNS --------------------------------------------------------- */ - /** - * Insert or assign an element. - * - * @param key Key to be mapped or search for. - * @param value Value to insert or assign. - * @return {@link Pair} of an iterator to the newly inserted element and `true`, if the specified *key* doesn't exist, otherwise {@link Pair} of iterator to the ordinary element and `false`. - */ - public insert_or_assign(key: Key, value: T): Pair; - - /** - * Insert or assign an element with hint. - * - * @param hint Hint for the position where the element can be inserted. - * @param key Key to be mapped or search for. - * @param value Value to insert or assign. - * @return An iterator to the newly inserted element, if the specified key doesn't exist, otherwise an iterator to the ordinary element. - */ - public insert_or_assign(hint: Iterator, key: Key, value: T): Iterator; - - public insert_or_assign(...args: any[]): any { - if (args.length === 2) { - return this._Insert_or_assign_with_key_value(args[0], args[1]); - } else if (args.length === 3) { - // INSERT OR ASSIGN AN ELEMENT - return this._Insert_or_assign_with_hint(args[0], args[1], args[2]); - } + /** + * Insert or assign an element. + * + * @param key Key to be mapped or search for. + * @param value Value to insert or assign. + * @return {@link Pair} of an iterator to the newly inserted element and `true`, if the specified *key* doesn't exist, otherwise {@link Pair} of iterator to the ordinary element and `false`. + */ + public insert_or_assign(key: Key, value: T): Pair; + + /** + * Insert or assign an element with hint. + * + * @param hint Hint for the position where the element can be inserted. + * @param key Key to be mapped or search for. + * @param value Value to insert or assign. + * @return An iterator to the newly inserted element, if the specified key doesn't exist, otherwise an iterator to the ordinary element. + */ + public insert_or_assign(hint: Iterator, key: Key, value: T): Iterator; + + public insert_or_assign(...args: any[]): any { + if (args.length === 2) { + return this._Insert_or_assign_with_key_value(args[0], args[1]); + } else if (args.length === 3) { + // INSERT OR ASSIGN AN ELEMENT + return this._Insert_or_assign_with_hint(args[0], args[1], args[2]); } - - private _Insert_or_assign_with_key_value( - key: Key, - value: T, - ): Pair { - const ret = this.emplace(key, value); - if (ret.second === false) ret.first.second = value; - - return ret; - } - - private _Insert_or_assign_with_hint( - hint: Iterator, - key: Key, - value: T, - ): Iterator { - const ret = this.emplace_hint(hint, key, value); - if (ret.second !== value) ret.second = value; - - return ret; - } - - /* --------------------------------------------------------- + } + + private _Insert_or_assign_with_key_value( + key: Key, + value: T, + ): Pair { + const ret = this.emplace(key, value); + if (ret.second === false) ret.first.second = value; + + return ret; + } + + private _Insert_or_assign_with_hint( + hint: Iterator, + key: Key, + value: T, + ): Iterator { + const ret = this.emplace_hint(hint, key, value); + if (ret.second !== value) ret.second = value; + + return ret; + } + + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - /** - * Extract an element by key. - * - * @param key Key to search for. - * @return The extracted element. - */ - public extract(key: Key): Entry; - - /** - * Extract an element by iterator. - * - * @param pos The iterator to the element for extraction. - * @return Iterator following the *pos*, strained by the extraction. - */ - public extract(pos: Iterator): Iterator; - - public extract(param: Key | Iterator): any { - if (param instanceof this.end().constructor) - return this._Extract_by_iterator(param as Iterator); - else return this._Extract_by_key(param as Key); - } - - private _Extract_by_key(key: Key): Entry { - const it = this.find(key); - if (it.equals(this.end()) === true) - throw ErrorGenerator.key_nout_found(this, "extract", key); - - const ret: Entry = it.value; - this._Erase_by_range(it); - - return ret; - } - - private _Extract_by_iterator(it: Iterator): Iterator { - if (it.equals(this.end()) === true) return this.end(); - - this._Erase_by_range(it); - return it; - } - - protected _Erase_by_key(key: Key): number { - const it = this.find(key); - if (it.equals(this.end()) === true) return 0; - - this._Erase_by_range(it); - return 1; - } - - /* --------------------------------------------------------- + /** + * Extract an element by key. + * + * @param key Key to search for. + * @return The extracted element. + */ + public extract(key: Key): Entry; + + /** + * Extract an element by iterator. + * + * @param pos The iterator to the element for extraction. + * @return Iterator following the *pos*, strained by the extraction. + */ + public extract(pos: Iterator): Iterator; + + public extract(param: Key | Iterator): any { + if (param instanceof this.end().constructor) + return this._Extract_by_iterator(param as Iterator); + else return this._Extract_by_key(param as Key); + } + + private _Extract_by_key(key: Key): Entry { + const it = this.find(key); + if (it.equals(this.end()) === true) + throw ErrorGenerator.key_nout_found(this, "extract", key); + + const ret: Entry = it.value; + this._Erase_by_range(it); + + return ret; + } + + private _Extract_by_iterator(it: Iterator): Iterator { + if (it.equals(this.end()) === true) return this.end(); + + this._Erase_by_range(it); + return it; + } + + protected _Erase_by_key(key: Key): number { + const it = this.find(key); + if (it.equals(this.end()) === true) return 0; + + this._Erase_by_range(it); + return 1; + } + + /* --------------------------------------------------------- UTILITY --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public merge(source: Source): void { - for (let it = source.begin(); !it.equals(source.end()); ) - if (this.has(it.first) === false) { - this.insert(it.value); - it = source.erase(it); - } else it = it.next(); - } + /** + * @inheritDoc + */ + public merge(source: Source): void { + for (let it = source.begin(); !it.equals(source.end()); ) + if (this.has(it.first) === false) { + this.insert(it.value); + it = source.erase(it); + } else it = it.next(); + } } /** * */ export namespace UniqueMap { - /** - * Iterator of {@link UniqueMap} - * - * @author Jenogho Nam - */ - export type Iterator< - Key, - T, - SourceT extends UniqueMap, - IteratorT extends Iterator, - ReverseT extends ReverseIterator, - > = MapContainer.Iterator; - - /** - * Reverse iterator of {@link UniqueMap} - * - * @author Jenogho Nam - */ - export type ReverseIterator< - Key, - T, - SourceT extends UniqueMap, - IteratorT extends Iterator, - ReverseT extends ReverseIterator, - > = MapContainer.ReverseIterator< - Key, - T, - true, - SourceT, - IteratorT, - ReverseT - >; + /** + * Iterator of {@link UniqueMap} + * + * @author Jenogho Nam + */ + export type Iterator< + Key, + T, + SourceT extends UniqueMap, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = MapContainer.Iterator; + + /** + * Reverse iterator of {@link UniqueMap} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + Key, + T, + SourceT extends UniqueMap, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = MapContainer.ReverseIterator; } diff --git a/src/base/container/UniqueSet.ts b/src/base/container/UniqueSet.ts index fb4c4272..6a96d1a5 100644 --- a/src/base/container/UniqueSet.ts +++ b/src/base/container/UniqueSet.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std.base */ //================================================================ -import { SetContainer } from "./SetContainer"; - +import { ErrorGenerator } from "../../internal/exception/ErrorGenerator"; import { IForwardIterator } from "../../iterator/IForwardIterator"; import { Pair } from "../../utility/Pair"; -import { ErrorGenerator } from "../../internal/exception/ErrorGenerator"; +import { SetContainer } from "./SetContainer"; /** * Basic set container blocking duplicated key. @@ -21,158 +21,153 @@ import { ErrorGenerator } from "../../internal/exception/ErrorGenerator"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class UniqueSet< - Key, - Source extends UniqueSet, - IteratorT extends UniqueSet.Iterator, - ReverseT extends UniqueSet.ReverseIterator< - Key, - Source, - IteratorT, - ReverseT - >, + Key, + Source extends UniqueSet, + IteratorT extends UniqueSet.Iterator, + ReverseT extends UniqueSet.ReverseIterator, > extends SetContainer { - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSOR --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public count(key: Key): number { - return this.find(key).equals(this.end()) ? 0 : 1; - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public count(key: Key): number { + return this.find(key).equals(this.end()) ? 0 : 1; + } + + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - /** - * Insert an element. - * - * @param key Key to insert. - * @return {@link Pair} of an iterator to the newly inserted element and `true`, if the specified *key* doesn't exist, otherwise {@link Pair} of iterator to ordinary element and `false`. - */ - public insert(key: Key): Pair; - - /** - * Insert an element with hint. - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A tuple to be referenced for the insert. - * @return An iterator to the newly inserted element, if the specified key doesn't exist, otherwise an iterator to the ordinary element. - */ - public insert(hint: IteratorT, key: Key): IteratorT; - - /** - * Insert range elements. - * - * @param first Input iterator of the first position. - * @param last Input iteartor of the last position. - */ - public insert< - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void; - - public insert(...args: any[]): any { - return (super.insert as Function)(...args); - } - - protected _Insert_by_range< - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void { - for (; !first.equals(last); first = first.next()) - this._Insert_by_key(first.value); - } - - /* --------------------------------------------------------- + /** + * Insert an element. + * + * @param key Key to insert. + * @return {@link Pair} of an iterator to the newly inserted element and `true`, if the specified *key* doesn't exist, otherwise {@link Pair} of iterator to ordinary element and `false`. + */ + public insert(key: Key): Pair; + + /** + * Insert an element with hint. + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A tuple to be referenced for the insert. + * @return An iterator to the newly inserted element, if the specified key doesn't exist, otherwise an iterator to the ordinary element. + */ + public insert(hint: IteratorT, key: Key): IteratorT; + + /** + * Insert range elements. + * + * @param first Input iterator of the first position. + * @param last Input iteartor of the last position. + */ + public insert< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void; + + public insert(...args: any[]): any { + return (super.insert as Function)(...args); + } + + protected _Insert_by_range< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void { + for (; !first.equals(last); first = first.next()) + this._Insert_by_key(first.value); + } + + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - /** - * Extract an element by key. - * - * @param key Key to search for. - * @return The extracted element. - */ - public extract(key: Key): Key; - - /** - * Extract an element by iterator. - * - * @param pos The iterator to the element for extraction. - * @return Iterator following the *pos*, strained by the extraction. - */ - public extract(it: IteratorT): IteratorT; - - public extract(param: Key | IteratorT): any { - if (param instanceof this.end().constructor) - return this._Extract_by_iterator(param as IteratorT); - else return this._Extract_by_val(param as Key); - } - - private _Extract_by_val(key: Key): Key { - const it = this.find(key); - if (it.equals(this.end()) === true) - throw ErrorGenerator.key_nout_found(this, "extract", key); - - this._Erase_by_range(it); - return key; - } - - private _Extract_by_iterator(it: IteratorT): IteratorT { - if (it.equals(this.end()) === true || this.has(it.value) === false) - return this.end(); - - this._Erase_by_range(it); - return it; - } - - protected _Erase_by_val(key: Key): number { - const it = this.find(key); - if (it.equals(this.end()) === true) return 0; - - this._Erase_by_range(it); - return 1; - } - - /* --------------------------------------------------------- + /** + * Extract an element by key. + * + * @param key Key to search for. + * @return The extracted element. + */ + public extract(key: Key): Key; + + /** + * Extract an element by iterator. + * + * @param pos The iterator to the element for extraction. + * @return Iterator following the *pos*, strained by the extraction. + */ + public extract(it: IteratorT): IteratorT; + + public extract(param: Key | IteratorT): any { + if (param instanceof this.end().constructor) + return this._Extract_by_iterator(param as IteratorT); + else return this._Extract_by_val(param as Key); + } + + private _Extract_by_val(key: Key): Key { + const it = this.find(key); + if (it.equals(this.end()) === true) + throw ErrorGenerator.key_nout_found(this, "extract", key); + + this._Erase_by_range(it); + return key; + } + + private _Extract_by_iterator(it: IteratorT): IteratorT { + if (it.equals(this.end()) === true || this.has(it.value) === false) + return this.end(); + + this._Erase_by_range(it); + return it; + } + + protected _Erase_by_val(key: Key): number { + const it = this.find(key); + if (it.equals(this.end()) === true) return 0; + + this._Erase_by_range(it); + return 1; + } + + /* --------------------------------------------------------- UTILITY --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public merge(source: Source): void { - for (let it = source.begin(); !it.equals(source.end()); ) { - if (this.has(it.value) === false) { - this.insert(it.value); - it = source.erase(it); - } else it = it.next(); - } + /** + * @inheritDoc + */ + public merge(source: Source): void { + for (let it = source.begin(); !it.equals(source.end()); ) { + if (this.has(it.value) === false) { + this.insert(it.value); + it = source.erase(it); + } else it = it.next(); } + } } /** * */ export namespace UniqueSet { - /** - * Iterator of {@link UniqueSet} - * - * @author Jenogho Nam - */ - export type Iterator< - Key, - SourceT extends UniqueSet, - IteratorT extends Iterator, - ReverseT extends ReverseIterator, - > = SetContainer.Iterator; - - /** - * Reverse iterator of {@link UniqueSet} - * - * @author Jenogho Nam - */ - export type ReverseIterator< - Key, - SourceT extends UniqueSet, - IteratorT extends Iterator, - ReverseT extends ReverseIterator, - > = SetContainer.ReverseIterator; + /** + * Iterator of {@link UniqueSet} + * + * @author Jenogho Nam + */ + export type Iterator< + Key, + SourceT extends UniqueSet, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = SetContainer.Iterator; + + /** + * Reverse iterator of {@link UniqueSet} + * + * @author Jenogho Nam + */ + export type ReverseIterator< + Key, + SourceT extends UniqueSet, + IteratorT extends Iterator, + ReverseT extends ReverseIterator, + > = SetContainer.ReverseIterator; } diff --git a/src/base/index.ts b/src/base/index.ts index c4c7192d..84c91217 100644 --- a/src/base/index.ts +++ b/src/base/index.ts @@ -1,4 +1,5 @@ //================================================================ + /** * Basic Features * diff --git a/src/base/thread/ILockable.ts b/src/base/thread/ILockable.ts index d2099efd..7a5f367b 100644 --- a/src/base/thread/ILockable.ts +++ b/src/base/thread/ILockable.ts @@ -10,58 +10,58 @@ * @author Jeongho Nam - https://github.com/samchon */ export interface ILockable { - /** - * Locks the mutex. - * - * Monopolies a mutex until be {@link unlock unlocked}. If there're someone who have already - * {@link lock monopolied} the mutex, the function call would be blocked until all of them to - * return their acquistions by calling the {@link unlock} method. - * - * In same reason, if you don't call the {@link unlock} function after your business, the - * others who want to {@link lock monopoly} the mutex would be fall into the forever sleep. - * Therefore, never forget to calling the {@link unlock} function or utilize the - * {@link UniqueLock.lock} function instead to ensure the safety. - */ - lock(): Promise; + /** + * Locks the mutex. + * + * Monopolies a mutex until be {@link unlock unlocked}. If there're someone who have already + * {@link lock monopolied} the mutex, the function call would be blocked until all of them to + * return their acquistions by calling the {@link unlock} method. + * + * In same reason, if you don't call the {@link unlock} function after your business, the + * others who want to {@link lock monopoly} the mutex would be fall into the forever sleep. + * Therefore, never forget to calling the {@link unlock} function or utilize the + * {@link UniqueLock.lock} function instead to ensure the safety. + */ + lock(): Promise; - /** - * Tries to lock the mutex. - * - * Attempts to monopoly a mutex without blocking. If succeeded to monopoly the mutex - * immediately, it returns `true` directly. Otherwise there's someone who has already - * {@link lock monopolied} the mutex, the function gives up the trial immediately and returns - * `false` directly. - * - * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the - * {@link unlock} function after your business, the others who want to {@link lock monopoly} - * the mutex would be fall into the forever sleep. Therefore, never forget to calling the - * {@link unlock} function or utilize the {@link UniqueLock.try_lock} function instead to - * ensure the safety. - * - * @return Whether succeeded to monopoly the mutex or not. - */ - try_lock(): Promise; + /** + * Tries to lock the mutex. + * + * Attempts to monopoly a mutex without blocking. If succeeded to monopoly the mutex + * immediately, it returns `true` directly. Otherwise there's someone who has already + * {@link lock monopolied} the mutex, the function gives up the trial immediately and returns + * `false` directly. + * + * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the + * {@link unlock} function after your business, the others who want to {@link lock monopoly} + * the mutex would be fall into the forever sleep. Therefore, never forget to calling the + * {@link unlock} function or utilize the {@link UniqueLock.try_lock} function instead to + * ensure the safety. + * + * @return Whether succeeded to monopoly the mutex or not. + */ + try_lock(): Promise; - /** - * Unlocks the mutex. - * - * When you call this {@link unlock} method and there're someone who are currently blocked by - * attempting to {@link lock} this mutex, one of them (FIFO; first-in-first-out) would acquire - * the lock and continues its execution. - * - * Otherwise, there's not anyone who is acquiring the {@link lock} of this mutex, the - * {@link DomainError} exception would be thrown. - * - * > As you know, when you succeeded to acquire the `lock`, you don't have to forget to - * > calling this {@link unlock} method after your business. If you forget it, it would be a - * > terrible situation for the others who're attempting to lock this mutex. - * > - * > However, if you utilize the {@link UniqueLock}, you don't need to consider about this - * > {@link unlock} method. Just define your business into a callback function as a parameter - * > of methods of the {@link UniqueLock}, then this {@link unlock} method would be - * > automatically called by the {@link UniqueLock} after the business. - * - * @throw {@link DomainError} when no one is acquiring the {@link lock write lock}. - */ - unlock(): Promise; + /** + * Unlocks the mutex. + * + * When you call this {@link unlock} method and there're someone who are currently blocked by + * attempting to {@link lock} this mutex, one of them (FIFO; first-in-first-out) would acquire + * the lock and continues its execution. + * + * Otherwise, there's not anyone who is acquiring the {@link lock} of this mutex, the + * {@link DomainError} exception would be thrown. + * + * > As you know, when you succeeded to acquire the `lock`, you don't have to forget to + * > calling this {@link unlock} method after your business. If you forget it, it would be a + * > terrible situation for the others who're attempting to lock this mutex. + * > + * > However, if you utilize the {@link UniqueLock}, you don't need to consider about this + * > {@link unlock} method. Just define your business into a callback function as a parameter + * > of methods of the {@link UniqueLock}, then this {@link unlock} method would be + * > automatically called by the {@link UniqueLock} after the business. + * + * @throw {@link DomainError} when no one is acquiring the {@link lock write lock}. + */ + unlock(): Promise; } diff --git a/src/base/thread/ISharedLockable.ts b/src/base/thread/ISharedLockable.ts index 390c4216..e5bd17bf 100644 --- a/src/base/thread/ISharedLockable.ts +++ b/src/base/thread/ISharedLockable.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.base @@ -12,117 +13,117 @@ import { ILockable } from "./ILockable"; * @author Jeongho Nam - https://github.com/samchon */ export interface ISharedLockable extends ILockable { - /* --------------------------------------------------------- + /* --------------------------------------------------------- WRITE LOCK --------------------------------------------------------- */ - /** - * Write locks the mutex. - * - * Monopolies a mutex until be {@link unlock unlocked}. If there're someone who have already - * {@link lock monopolied} or {@link lock_shared shared} the mutex, the function call would - * be blocked until all of them to return their acquistions by calling {@link unlock} or - * {@link unlock_shared} methods. - * - * In same reason, if you don't call the {@link unlock} function after your business, the - * others who want to {@link lock monopoly} or {@link lock_shared share} the mutex would be - * fall into the forever sleep. Therefore, never forget to calling the {@link unlock} function - * or utilize the {@link UniqueLock.lock} function instead to ensure the safety. - */ - lock(): Promise; + /** + * Write locks the mutex. + * + * Monopolies a mutex until be {@link unlock unlocked}. If there're someone who have already + * {@link lock monopolied} or {@link lock_shared shared} the mutex, the function call would + * be blocked until all of them to return their acquistions by calling {@link unlock} or + * {@link unlock_shared} methods. + * + * In same reason, if you don't call the {@link unlock} function after your business, the + * others who want to {@link lock monopoly} or {@link lock_shared share} the mutex would be + * fall into the forever sleep. Therefore, never forget to calling the {@link unlock} function + * or utilize the {@link UniqueLock.lock} function instead to ensure the safety. + */ + lock(): Promise; - /** - * Tries to write lock the mutex. - * - * Attempts to monopoly a mutex without blocking. If succeeded to monopoly the mutex - * immediately, it returns `true` directly. Otherwise there's someone who has already - * {@link lock monopolied} or {@link lock_shared shared} the mutex, the function gives up the - * trial immediately and returns `false` directly. - * - * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the - * {@link unlock} function after your business, the others who want to {@link lock monopoly} - * or {@link lock_shared share} the mutex would be fall into the forever sleep. Therefore, - * never forget to calling the {@link unlock} function or utilize the - * {@link UniqueLock.try_lock} function instead to ensure the safety. - * - * @return Whether succeeded to monopoly the mutex or not. - */ - try_lock(): Promise; + /** + * Tries to write lock the mutex. + * + * Attempts to monopoly a mutex without blocking. If succeeded to monopoly the mutex + * immediately, it returns `true` directly. Otherwise there's someone who has already + * {@link lock monopolied} or {@link lock_shared shared} the mutex, the function gives up the + * trial immediately and returns `false` directly. + * + * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the + * {@link unlock} function after your business, the others who want to {@link lock monopoly} + * or {@link lock_shared share} the mutex would be fall into the forever sleep. Therefore, + * never forget to calling the {@link unlock} function or utilize the + * {@link UniqueLock.try_lock} function instead to ensure the safety. + * + * @return Whether succeeded to monopoly the mutex or not. + */ + try_lock(): Promise; - /** - * Write unlocks the mutex. - * - * When you call this {@link unlock} method and there're someone who are currently blocked by - * attempting to {@link lock write} or {@link lock_shared read} lock this mutex, one of them - * (FIFO; first-in-first-out) would acquire the lock and continues its execution. - * - * Otherwise, there's not anyone who is acquiring the {@link lock write lock} of this mutex, - * the {@link DomainError} exception would be thrown. - * - * > As you know, when you succeeded to acquire the `write lock`, you don't have to forget to - * > calling this {@link unlock} method after your business. If you forget it, it would be a - * > terrible situation for the others who're attempting to lock this mutex. - * > - * > However, if you utilize the {@link UniqueLock}, you don't need to consider about this - * > {@link unlock} method. Just define your business into a callback function as a parameter - * > of methods of the {@link UniqueLock}, then this {@link unlock} method would be - * > automatically called by the {@link UniqueLock} after the business. - * - * @throw {@link DomainError} when no one is acquiring the {@link lock write lock}. - */ - unlock(): Promise; + /** + * Write unlocks the mutex. + * + * When you call this {@link unlock} method and there're someone who are currently blocked by + * attempting to {@link lock write} or {@link lock_shared read} lock this mutex, one of them + * (FIFO; first-in-first-out) would acquire the lock and continues its execution. + * + * Otherwise, there's not anyone who is acquiring the {@link lock write lock} of this mutex, + * the {@link DomainError} exception would be thrown. + * + * > As you know, when you succeeded to acquire the `write lock`, you don't have to forget to + * > calling this {@link unlock} method after your business. If you forget it, it would be a + * > terrible situation for the others who're attempting to lock this mutex. + * > + * > However, if you utilize the {@link UniqueLock}, you don't need to consider about this + * > {@link unlock} method. Just define your business into a callback function as a parameter + * > of methods of the {@link UniqueLock}, then this {@link unlock} method would be + * > automatically called by the {@link UniqueLock} after the business. + * + * @throw {@link DomainError} when no one is acquiring the {@link lock write lock}. + */ + unlock(): Promise; - /* --------------------------------------------------------- + /* --------------------------------------------------------- READ LOCK --------------------------------------------------------- */ - /** - * Read locks the mutex. - * - * Shares a mutex until be {@link unlock_shared unlocked}. If there're someone who have - * already {@link lock monopolied} the mutex, the function call would be blocked until all of - * them to {@link unlock return} their acquisitions. - * - * In same reason, if you don't call the {@link unlock_shared} function after your business, - * the others who want to {@link lock monopoly} the mutex would be fall into the forever - * sleep. Therefore, never forget to calling the {@link unlock_shared} or utilize the - * {@link SharedLock.lock} function instead to ensure the safety. - */ - lock_shared(): Promise; + /** + * Read locks the mutex. + * + * Shares a mutex until be {@link unlock_shared unlocked}. If there're someone who have + * already {@link lock monopolied} the mutex, the function call would be blocked until all of + * them to {@link unlock return} their acquisitions. + * + * In same reason, if you don't call the {@link unlock_shared} function after your business, + * the others who want to {@link lock monopoly} the mutex would be fall into the forever + * sleep. Therefore, never forget to calling the {@link unlock_shared} or utilize the + * {@link SharedLock.lock} function instead to ensure the safety. + */ + lock_shared(): Promise; - /** - * Tries to read lock the mutex. - * - * Attemps to share a mutex without blocking. If succeeded to share the mutex immediately, it - * returns `true` directly. Otherwise there's someone who has already {@link lock monopolied} - * the mutex, the function gives up the trial immediately and returns `false` directly. - * - * Note that, if you succeeded to share the mutex (returns `true`) but do not call the - * {@link unlock_shared} function after your buinsess, the others who want to - * {@link lock monopoly} the mutex would be fall into the forever sleep. Therefore, never - * forget to calling the {@link unlock_shared} function or utilize the - * {@link SharedLock.try_lock} function instead to ensure the safety. - * - * @return Whether succeeded to share the mutex or not. - */ - try_lock_shared(): Promise; + /** + * Tries to read lock the mutex. + * + * Attemps to share a mutex without blocking. If succeeded to share the mutex immediately, it + * returns `true` directly. Otherwise there's someone who has already {@link lock monopolied} + * the mutex, the function gives up the trial immediately and returns `false` directly. + * + * Note that, if you succeeded to share the mutex (returns `true`) but do not call the + * {@link unlock_shared} function after your buinsess, the others who want to + * {@link lock monopoly} the mutex would be fall into the forever sleep. Therefore, never + * forget to calling the {@link unlock_shared} function or utilize the + * {@link SharedLock.try_lock} function instead to ensure the safety. + * + * @return Whether succeeded to share the mutex or not. + */ + try_lock_shared(): Promise; - /** - * Read unlocks the mutex. - * - * When you call this {@link unlock_shared} method and there're someone who are currently - * blocked by attempting to {@link lock monopoly} this mutex, one of them - * (FIFO; first-in-first-out) would acquire the lock and continues its execution. - * - * Otherwise, there's not anyone who is acquiring the {@link lock_shared read lock} of this - * mutex, the {@link DomainError} exception would be thrown. - * - * > As you know, when you succeeded to acquire the `read lock`, you don't have to forget to - * > calling this {@link unlock_shared} method after your business. If you forget it, it would - * > be a terrible situation for the others who're attempting to lock this mutex. - * > - * > However, if you utilize the {@link SharedLock}, you don't need to consider about this - * > {@link unlock_shared} method. Just define your business into a callback function as a - * > parameter of methods of the {@link SharedLock}, then this {@link unlock_shared} method - * > would be automatically called by the {@link SharedLock} after the business. - */ - unlock_shared(): Promise; + /** + * Read unlocks the mutex. + * + * When you call this {@link unlock_shared} method and there're someone who are currently + * blocked by attempting to {@link lock monopoly} this mutex, one of them + * (FIFO; first-in-first-out) would acquire the lock and continues its execution. + * + * Otherwise, there's not anyone who is acquiring the {@link lock_shared read lock} of this + * mutex, the {@link DomainError} exception would be thrown. + * + * > As you know, when you succeeded to acquire the `read lock`, you don't have to forget to + * > calling this {@link unlock_shared} method after your business. If you forget it, it would + * > be a terrible situation for the others who're attempting to lock this mutex. + * > + * > However, if you utilize the {@link SharedLock}, you don't need to consider about this + * > {@link unlock_shared} method. Just define your business into a callback function as a + * > parameter of methods of the {@link SharedLock}, then this {@link unlock_shared} method + * > would be automatically called by the {@link SharedLock} after the business. + */ + unlock_shared(): Promise; } diff --git a/src/base/thread/ISharedTimedLockable.ts b/src/base/thread/ISharedTimedLockable.ts index df497f10..d358d228 100644 --- a/src/base/thread/ISharedTimedLockable.ts +++ b/src/base/thread/ISharedTimedLockable.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.base @@ -12,97 +13,97 @@ import { ISharedLockable } from "./ISharedLockable"; * @author Jeongho Nam - https://github.com/samchon */ export interface ISharedTimedLockable extends ISharedLockable { - /* --------------------------------------------------------- + /* --------------------------------------------------------- WRITE LOCK --------------------------------------------------------- */ - /** - * Tries to write lock the mutex until timeout. - * - * Attempts to monopoly a mutex until timeout. If succeeded to monopoly the mutex until the - * timeout, it returns `true`. Otherwise failed to acquiring the lock in the given time, the - * function gives up the trial and returns `false`. - * - * Failed to acquiring the lock in the given time (returns `false`), it means that there's - * someone who has already {@link lock monopolied} or {@link lock_shared shared} the mutex and - * does not return it over the timeout. - * - * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the - * {@link unlock} function after your business, the others who want to {@link lock monopoly} - * or {@link lock_shared share} the mutex would be fall into the forever sleep. Therefore, - * never forget to calling the {@link unlock} function or utilize the - * {@link UniqueLock.try_lock_for} function instead to ensure the safety. - * - * @param ms The maximum miliseconds for waiting. - * @return Whether succeeded to monopoly the mutex or not. - */ - try_lock_for(ms: number): Promise; + /** + * Tries to write lock the mutex until timeout. + * + * Attempts to monopoly a mutex until timeout. If succeeded to monopoly the mutex until the + * timeout, it returns `true`. Otherwise failed to acquiring the lock in the given time, the + * function gives up the trial and returns `false`. + * + * Failed to acquiring the lock in the given time (returns `false`), it means that there's + * someone who has already {@link lock monopolied} or {@link lock_shared shared} the mutex and + * does not return it over the timeout. + * + * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the + * {@link unlock} function after your business, the others who want to {@link lock monopoly} + * or {@link lock_shared share} the mutex would be fall into the forever sleep. Therefore, + * never forget to calling the {@link unlock} function or utilize the + * {@link UniqueLock.try_lock_for} function instead to ensure the safety. + * + * @param ms The maximum miliseconds for waiting. + * @return Whether succeeded to monopoly the mutex or not. + */ + try_lock_for(ms: number): Promise; - /** - * Tries to write lock the mutex until time expiration. - * - * Attemps to monopoly a mutex until time expiration. If succeeded to monopoly the mutex - * until the time expiration, it returns `true`. Otherwise failed to acquiring the lock in the - * given time, the function gives up the trial and returns `false`. - * - * Failed to acquiring the lock in the given time (returns `false`), it means that there's - * someone who has already {@link lock monopolied} or {@link lock_shared shared} the mutex and - * does not return it over the time expiration. - * - * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the - * {@link unlock} function after your business, the others who want to {@link lock monopoly} - * or {@link lock_shared share} the mutex would be fall into the forever sleep. Therefore, - * never forget to calling the {@link unlock} function or utilize the - * {@link UniqueLock.try_lock_until} function instead to ensure the safety. - * - * @param at The maximum time point to wait. - * @return Whether succeeded to monopoly the mutex or not. - */ - try_lock_until(at: Date): Promise; + /** + * Tries to write lock the mutex until time expiration. + * + * Attemps to monopoly a mutex until time expiration. If succeeded to monopoly the mutex + * until the time expiration, it returns `true`. Otherwise failed to acquiring the lock in the + * given time, the function gives up the trial and returns `false`. + * + * Failed to acquiring the lock in the given time (returns `false`), it means that there's + * someone who has already {@link lock monopolied} or {@link lock_shared shared} the mutex and + * does not return it over the time expiration. + * + * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the + * {@link unlock} function after your business, the others who want to {@link lock monopoly} + * or {@link lock_shared share} the mutex would be fall into the forever sleep. Therefore, + * never forget to calling the {@link unlock} function or utilize the + * {@link UniqueLock.try_lock_until} function instead to ensure the safety. + * + * @param at The maximum time point to wait. + * @return Whether succeeded to monopoly the mutex or not. + */ + try_lock_until(at: Date): Promise; - /* --------------------------------------------------------- + /* --------------------------------------------------------- READ LOCK --------------------------------------------------------- */ - /** - * Tries to read lock the mutex until timeout. - * - * Attemps to share a mutex until timeout. If succeeded to share the mutex until timeout, it - * returns `true`. Otherwise failed to acquiring the shared lock in the given time, the - * function gives up the trial and returns `false`. - * - * Failed to acquring the shared lock in the given time (returns `false`), it means that - * there's someone who has already {@link lock monopolied} the mutex and does not return it - * over the timeout. - * - * Note that, if you succeeded to share the mutex (returns `true`) but do not call the - * {@link unlock_shared} function after your buinsess, the others who want to - * {@link lock monopoly} the mutex would be fall into the forever sleep. Therefore, never - * forget to calling the {@link unlock_shared} function or utilize the - * {@link SharedLock.try_lock_for} function instead to ensure the safety. - * - * @param ms The maximum miliseconds for waiting. - * @return Whether succeeded to share the mutex or not. - */ - try_lock_shared_for(ms: number): Promise; + /** + * Tries to read lock the mutex until timeout. + * + * Attemps to share a mutex until timeout. If succeeded to share the mutex until timeout, it + * returns `true`. Otherwise failed to acquiring the shared lock in the given time, the + * function gives up the trial and returns `false`. + * + * Failed to acquring the shared lock in the given time (returns `false`), it means that + * there's someone who has already {@link lock monopolied} the mutex and does not return it + * over the timeout. + * + * Note that, if you succeeded to share the mutex (returns `true`) but do not call the + * {@link unlock_shared} function after your buinsess, the others who want to + * {@link lock monopoly} the mutex would be fall into the forever sleep. Therefore, never + * forget to calling the {@link unlock_shared} function or utilize the + * {@link SharedLock.try_lock_for} function instead to ensure the safety. + * + * @param ms The maximum miliseconds for waiting. + * @return Whether succeeded to share the mutex or not. + */ + try_lock_shared_for(ms: number): Promise; - /** - * Tries to read lock the mutex until time expiration. - * - * Attemps to share a mutex until time expiration. If succeeded to share the mutex until time - * expiration, it returns `true`. Otherwise failed to acquiring the shared lock in the given - * time, the function gives up the trial and returns `false`. - * - * Failed to acquring the shared lock in the given time (returns `false`), it means that - * there's someone who has already {@link lock monopolied} the mutex and does not return it - * over the time expiration. - * - * Note that, if you succeeded to share the mutex (returns `true`) but do not call the - * {@link unlock_shared} function after your buinsess, the others who want to - * {@link lock monopoly} the mutex would be fall into the forever sleep. Therefore, never - * forget to calling the {@link unlock_shared} function or utilize the - * {@link SharedLock.try_lock_until} function instead to ensure the safety. - * - * @param at The maximum time point to wait. - * @return Whether succeeded to share the mutex or not. - */ - try_lock_shared_until(at: Date): Promise; + /** + * Tries to read lock the mutex until time expiration. + * + * Attemps to share a mutex until time expiration. If succeeded to share the mutex until time + * expiration, it returns `true`. Otherwise failed to acquiring the shared lock in the given + * time, the function gives up the trial and returns `false`. + * + * Failed to acquring the shared lock in the given time (returns `false`), it means that + * there's someone who has already {@link lock monopolied} the mutex and does not return it + * over the time expiration. + * + * Note that, if you succeeded to share the mutex (returns `true`) but do not call the + * {@link unlock_shared} function after your buinsess, the others who want to + * {@link lock monopoly} the mutex would be fall into the forever sleep. Therefore, never + * forget to calling the {@link unlock_shared} function or utilize the + * {@link SharedLock.try_lock_until} function instead to ensure the safety. + * + * @param at The maximum time point to wait. + * @return Whether succeeded to share the mutex or not. + */ + try_lock_shared_until(at: Date): Promise; } diff --git a/src/base/thread/ITimedLockable.ts b/src/base/thread/ITimedLockable.ts index 837cea34..8f9db961 100644 --- a/src/base/thread/ITimedLockable.ts +++ b/src/base/thread/ITimedLockable.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.base @@ -12,47 +13,47 @@ import { ILockable } from "./ILockable"; * @author Jeongho Nam - https://github.com/samchon */ export interface ITimedLockable extends ILockable { - /** - * Tries to lock the mutex until timeout. - * - * Attempts to monopoly a mutex until timeout. If succeeded to monopoly the mutex until the - * timeout, it returns `true`. Otherwise failed to acquiring the lock in the given time, the - * function gives up the trial and returns `false`. - * - * Failed to acquiring the lock in the given time (returns `false`), it means that there's - * someone who has already {@link lock monopolied} the mutex and does not return it over the - * timeout. - * - * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the - * {@link unlock} function after your business, the others who want to {@link lock monopoly} - * the mutex would be fall into the forever sleep. Therefore, never forget to calling the - * {@link unlock} function or utilize the {@link UniqueLock.try_lock_for} function instead to - * ensure the safety. - * - * @param ms The maximum miliseconds for waiting. - * @return Whether succeeded to monopoly the mutex or not. - */ - try_lock_for(ms: number): Promise; + /** + * Tries to lock the mutex until timeout. + * + * Attempts to monopoly a mutex until timeout. If succeeded to monopoly the mutex until the + * timeout, it returns `true`. Otherwise failed to acquiring the lock in the given time, the + * function gives up the trial and returns `false`. + * + * Failed to acquiring the lock in the given time (returns `false`), it means that there's + * someone who has already {@link lock monopolied} the mutex and does not return it over the + * timeout. + * + * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the + * {@link unlock} function after your business, the others who want to {@link lock monopoly} + * the mutex would be fall into the forever sleep. Therefore, never forget to calling the + * {@link unlock} function or utilize the {@link UniqueLock.try_lock_for} function instead to + * ensure the safety. + * + * @param ms The maximum miliseconds for waiting. + * @return Whether succeeded to monopoly the mutex or not. + */ + try_lock_for(ms: number): Promise; - /** - * Tries to write lock the mutex until time expiration. - * - * Attemps to monopoly a mutex until time expiration. If succeeded to monopoly the mutex - * until the time expiration, it returns `true`. Otherwise failed to acquiring the lock in the - * given time, the function gives up the trial and returns `false`. - * - * Failed to acquiring the lock in the given time (returns `false`), it means that there's - * someone who has already {@link lock monopolied} the mutex and does not return it over the - * time expiration. - * - * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the - * {@link unlock} function after your business, the others who want to {@link lock monopoly} - * the mutex would be fall into the forever sleep. Therefore, never forget to calling the - * {@link unlock} function or utilize the {@link UniqueLock.try_lock_until} function instead - * to ensure the safety. - * - * @param at The maximum time point to wait. - * @return Whether succeeded to monopoly the mutex or not. - */ - try_lock_until(at: Date): Promise; + /** + * Tries to write lock the mutex until time expiration. + * + * Attemps to monopoly a mutex until time expiration. If succeeded to monopoly the mutex + * until the time expiration, it returns `true`. Otherwise failed to acquiring the lock in the + * given time, the function gives up the trial and returns `false`. + * + * Failed to acquiring the lock in the given time (returns `false`), it means that there's + * someone who has already {@link lock monopolied} the mutex and does not return it over the + * time expiration. + * + * Note that, if you succeeded to monopoly the mutex (returns `true`) but do not call the + * {@link unlock} function after your business, the others who want to {@link lock monopoly} + * the mutex would be fall into the forever sleep. Therefore, never forget to calling the + * {@link unlock} function or utilize the {@link UniqueLock.try_lock_until} function instead + * to ensure the safety. + * + * @param at The maximum time point to wait. + * @return Whether succeeded to monopoly the mutex or not. + */ + try_lock_until(at: Date): Promise; } diff --git a/src/benchmark/exceptions.ts b/src/benchmark/exceptions.ts index 501894ea..1fae337b 100644 --- a/src/benchmark/exceptions.ts +++ b/src/benchmark/exceptions.ts @@ -1,159 +1,158 @@ -import { Vector, List, ForwardList } from "../container/index"; +import { ForwardList, List, Vector } from "../container/index"; import { FlatMap } from "../experimental/container/FlatMap"; -import { SharedMutex } from "../thread/SharedMutex"; -import { Semaphore } from "../thread/Semaphore"; - import { advance } from "../iterator/global"; import { - cyl_bessel_j, - cyl_neumann, - cyl_bessel_i, - cyl_bessel_k, - ellint_3, - hermite, - assoc_laguerre, - assoc_legendre, + assoc_laguerre, + assoc_legendre, + cyl_bessel_i, + cyl_bessel_j, + cyl_bessel_k, + cyl_neumann, + ellint_3, + hermite, } from "../numeric/special_math/index"; +import { Semaphore } from "../thread/Semaphore"; +import { SharedMutex } from "../thread/SharedMutex"; async function except(proc: Procedure): Promise { - try { - await proc(); - } catch (exp) { - if (exp instanceof Error) return ` ${exp.name} | ${exp.message} `; - } - return " NULL | NULL "; + try { + await proc(); + } catch (exp) { + if (exp instanceof Error) return ` ${exp.name} | ${exp.message} `; + } + return " NULL | NULL "; } export async function main(): Promise { - let ret: string = - "# Exceptions\n" + " name | message \n" + "------|---------\n"; + let ret: string = + "# Exceptions\n" + " name | message \n" + "------|---------\n"; - const v: Vector = new Vector(); - const fl: ForwardList = new ForwardList(); - const l: List = new List(); - const m: FlatMap = new FlatMap(); - const mtx: SharedMutex = new SharedMutex(); - const sph: Semaphore<4> = new Semaphore(4); + const v: Vector = new Vector(); + const fl: ForwardList = new ForwardList(); + const l: List = new List(); + const m: FlatMap = new FlatMap(); + const mtx: SharedMutex = new SharedMutex(); + const sph: Semaphore<4> = new Semaphore(4); - const exceptions: string[] = [ - // VECTOR - await except(() => { - v.end().value; - }), - await except(() => { - v.at(1); - }), - await except(() => { - v.set(-1, 4); - }), - await except(() => { - v.set(1, 4); - }), - await except(() => { - v.insert(new Vector().begin(), 4); - }), - await except(() => { - v.insert(v.nth(-1), 4); - }), - await except(() => { - v.erase(new Vector().begin()); - }), - await except(() => { - v.erase(v.nth(-1)); - }), - await except(() => { - v.erase(v.nth(4), v.nth(2)); - }), + const exceptions: string[] = [ + // VECTOR + await except(() => { + v.end().value; + }), + await except(() => { + v.at(1); + }), + await except(() => { + v.set(-1, 4); + }), + await except(() => { + v.set(1, 4); + }), + await except(() => { + v.insert(new Vector().begin(), 4); + }), + await except(() => { + v.insert(v.nth(-1), 4); + }), + await except(() => { + v.erase(new Vector().begin()); + }), + await except(() => { + v.erase(v.nth(-1)); + }), + await except(() => { + v.erase(v.nth(4), v.nth(2)); + }), - // LIST - await except(() => { - l.insert(new List().begin(), 4); - }), - await except(() => { - l.erase(new List().begin()); - }), - await except(() => { - l.end().value; - }), - await except(() => { - l.end().value = 3; - }), - await except(() => { - fl.end().value; - }), - await except(() => { - fl.end().value = 3; - }), - await except(() => { - fl.before_begin().value; - }), - await except(() => { - fl.before_begin().value = 3; - }), + // LIST + await except(() => { + l.insert(new List().begin(), 4); + }), + await except(() => { + l.erase(new List().begin()); + }), + await except(() => { + l.end().value; + }), + await except(() => { + l.end().value = 3; + }), + await except(() => { + fl.end().value; + }), + await except(() => { + fl.end().value = 3; + }), + await except(() => { + fl.before_begin().value; + }), + await except(() => { + fl.before_begin().value = 3; + }), - // ASSOCIATIVE - await except(() => { - m.get(3); - }), - await except(() => { - m.extract(3); - }), - await except(() => { - m.end().value.second = 5; - }), - await except(() => { - m.find(3).second = 5; - }), + // ASSOCIATIVE + await except(() => { + m.get(3); + }), + await except(() => { + m.extract(3); + }), + await except(() => { + m.end().value.second = 5; + }), + await except(() => { + m.find(3).second = 5; + }), - // GLOBAL - await except(() => { - advance(fl.begin(), -4); - }), - await except(() => { - cyl_bessel_j(2.3, -5); - }), - await except(() => { - cyl_bessel_j(2.3, 0); - }), - await except(() => { - cyl_neumann(2.3, -4); - }), - await except(() => { - cyl_bessel_i(-2.1, -0.5); - }), - await except(() => { - cyl_bessel_i(2.3, 0); - }), - await except(() => { - cyl_bessel_k(1, -0.3); - }), - await except(() => { - const phi: number = 1.5; - const v: number = 1 / Math.pow(Math.sin(phi), 2) + 1; - ellint_3(0.5, v, phi); - }), - await except(() => { - hermite(-5, 2); - }), - await except(() => { - assoc_laguerre(-1, -1, 1); - }), - await except(() => { - assoc_legendre(-1, -1, 0.5); - }), - await except(() => { - assoc_legendre(0.5, 0.5, 2.5); - }), + // GLOBAL + await except(() => { + advance(fl.begin(), -4); + }), + await except(() => { + cyl_bessel_j(2.3, -5); + }), + await except(() => { + cyl_bessel_j(2.3, 0); + }), + await except(() => { + cyl_neumann(2.3, -4); + }), + await except(() => { + cyl_bessel_i(-2.1, -0.5); + }), + await except(() => { + cyl_bessel_i(2.3, 0); + }), + await except(() => { + cyl_bessel_k(1, -0.3); + }), + await except(() => { + const phi: number = 1.5; + const v: number = 1 / Math.pow(Math.sin(phi), 2) + 1; + ellint_3(0.5, v, phi); + }), + await except(() => { + hermite(-5, 2); + }), + await except(() => { + assoc_laguerre(-1, -1, 1); + }), + await except(() => { + assoc_legendre(-1, -1, 0.5); + }), + await except(() => { + assoc_legendre(0.5, 0.5, 2.5); + }), - // MUTEX - await except(() => mtx.unlock()), - await except(() => mtx.unlock_shared()), - await except(() => sph.release(0)), - await except(() => sph.release(5)), - await except(() => sph.release(2)), - ]; - ret += exceptions.join("\n") + "\n"; + // MUTEX + await except(() => mtx.unlock()), + await except(() => mtx.unlock_shared()), + await except(() => sph.release(0)), + await except(() => sph.release(5)), + await except(() => sph.release(2)), + ]; + ret += exceptions.join("\n") + "\n"; - return ret; + return ret; } type Procedure = () => void | Promise; diff --git a/src/benchmark/index.ts b/src/benchmark/index.ts index 388ea841..0f056615 100644 --- a/src/benchmark/index.ts +++ b/src/benchmark/index.ts @@ -1,65 +1,60 @@ +import fs from "fs"; + const EXTENSION = __filename.substr(-2); if (EXTENSION === "js") require("source-map-support").install(); -import fs from "fs"; - interface IModule { - main(): Promise; + main(): Promise; } const EXPORT_PATH: string = __dirname + "/../assets/benchmarks"; async function benchmark(feature: string): Promise { - //---- - // MAIN PROCESS - //---- - // LAZY CONSTRUCTION OF THE TARGET MODULE - const instance: IModule = await import(`${__dirname}/${feature}`); - let time: number = Date.now(); - - // CONTENT FROM THE SPEICAL MODULE - let content: string = await instance.main(); - time = Date.now() - time; - - //---- - // REPORT MEMORY USAGE - //---- - const memory: NodeJS.MemoryUsage = global.process.memoryUsage(); - let performance: string = - "> ## Performance \n" + `> - Elapsed time: ${time} ms\n`; - - for (const key in memory) { - const amount: number = - memory[key as keyof NodeJS.MemoryUsage] / 10 ** 6; - performance += `> - ${key}: ${amount} MB\n`; - } - content = performance + "\n\n" + content; - - //---- - // DO ARCHIVE - //---- - await fs.promises.writeFile( - `${EXPORT_PATH}/${feature}.md`, - content, - "utf8", - ); + //---- + // MAIN PROCESS + //---- + // LAZY CONSTRUCTION OF THE TARGET MODULE + const instance: IModule = await import(`${__dirname}/${feature}`); + let time: number = Date.now(); + + // CONTENT FROM THE SPEICAL MODULE + let content: string = await instance.main(); + time = Date.now() - time; + + //---- + // REPORT MEMORY USAGE + //---- + const memory: NodeJS.MemoryUsage = global.process.memoryUsage(); + let performance: string = + "> ## Performance \n" + `> - Elapsed time: ${time} ms\n`; + + for (const key in memory) { + const amount: number = memory[key as keyof NodeJS.MemoryUsage] / 10 ** 6; + performance += `> - ${key}: ${amount} MB\n`; + } + content = performance + "\n\n" + content; + + //---- + // DO ARCHIVE + //---- + await fs.promises.writeFile(`${EXPORT_PATH}/${feature}.md`, content, "utf8"); } async function main(): Promise { - try { - await fs.promises.mkdir(EXPORT_PATH); - } catch {} - - if (process.argv[2]) { - // SPECIFIED FEATURE EXISTS - await benchmark(process.argv[2]); - } else { - // ITERATE ALL FEATURES - const directory: string[] = await fs.promises.readdir(__dirname); - for (const file of directory) { - if (file.substr(-3) !== ".js" || file === "index.js") continue; - - await benchmark(file.substr(0, file.length - 3)); - } + try { + await fs.promises.mkdir(EXPORT_PATH); + } catch {} + + if (process.argv[2]) { + // SPECIFIED FEATURE EXISTS + await benchmark(process.argv[2]); + } else { + // ITERATE ALL FEATURES + const directory: string[] = await fs.promises.readdir(__dirname); + for (const file of directory) { + if (file.substr(-3) !== ".js" || file === "index.js") continue; + + await benchmark(file.substr(0, file.length - 3)); } + } } main(); diff --git a/src/benchmark/internal/TimeWatch.ts b/src/benchmark/internal/TimeWatch.ts index 2c5dbea9..cd2c0a77 100644 --- a/src/benchmark/internal/TimeWatch.ts +++ b/src/benchmark/internal/TimeWatch.ts @@ -1,7 +1,7 @@ export namespace TimeWatch { - export function measure(proc: () => void): number { - const time: number = Date.now(); - proc(); - return Date.now() - time; - } + export function measure(proc: () => void): number { + const time: number = Date.now(); + proc(); + return Date.now() - time; + } } diff --git a/src/benchmark/ranges.ts b/src/benchmark/ranges.ts index 210fa9b3..9c181f1c 100644 --- a/src/benchmark/ranges.ts +++ b/src/benchmark/ranges.ts @@ -4,43 +4,43 @@ import { TreeSet } from "../container/TreeSet"; import { Pair } from "../utility/Pair"; async function load(path: string): Promise>> { - const ret: TreeSet> = new TreeSet(); - const directory: string[] = await fs.promises.readdir(path); + const ret: TreeSet> = new TreeSet(); + const directory: string[] = await fs.promises.readdir(path); - for (const file of directory) { - if (file.substr(-3) !== ".js" || file === "index.js") continue; + for (const file of directory) { + if (file.substr(-3) !== ".js" || file === "index.js") continue; - const name: string = file.substr(0, file.length - 3); - const functions: IModule = await import(`${path}/${file}`); + const name: string = file.substr(0, file.length - 3); + const functions: IModule = await import(`${path}/${file}`); - for (const func in functions) ret.insert(new Pair(name, func)); - } - return ret; + for (const func in functions) ret.insert(new Pair(name, func)); + } + return ret; } export async function main(): Promise { - const std: TreeSet> = await load( - __dirname + "/../algorithm", - ); - const ranges: TreeSet> = await load( - __dirname + "/../ranges/algorithm", - ); - - const both: TreeSet> = new TreeSet(); - both.push(...std); - both.push(...ranges); - - let ret: string = - "## `` \n" + - " module | function | `std` | `std.ranges` \n" + - "--------|----------|-------|--------------\n"; - for (const pair of both) - ret += ` ${pair.first} | ${pair.second} | ${ - std.has(pair) ? "O" : "X" - } | ${ranges.has(pair) ? "O" : "X"} \n`; - return ret; + const std: TreeSet> = await load( + __dirname + "/../algorithm", + ); + const ranges: TreeSet> = await load( + __dirname + "/../ranges/algorithm", + ); + + const both: TreeSet> = new TreeSet(); + both.push(...std); + both.push(...ranges); + + let ret: string = + "## `` \n" + + " module | function | `std` | `std.ranges` \n" + + "--------|----------|-------|--------------\n"; + for (const pair of both) + ret += ` ${pair.first} | ${pair.second} | ${std.has(pair) ? "O" : "X"} | ${ + ranges.has(pair) ? "O" : "X" + } \n`; + return ret; } interface IModule { - [key: string]: Function | undefined; + [key: string]: Function | undefined; } diff --git a/src/benchmark/sorts.ts b/src/benchmark/sorts.ts index f154853e..8a1b4e1b 100644 --- a/src/benchmark/sorts.ts +++ b/src/benchmark/sorts.ts @@ -1,38 +1,35 @@ -import { Vector } from "../container/Vector"; +import { randint } from "../algorithm/random"; import { Deque } from "../container/Deque"; - +import { Vector } from "../container/Vector"; +import { sort } from "../ranges/algorithm/sorting"; import { StringUtil } from "./internal/StringUtil"; import { TimeWatch } from "./internal/TimeWatch"; -import { randint } from "../algorithm/random"; -import { sort } from "../ranges/algorithm/sorting"; - function watch(n: number): [number, number, number] { - const items: number[] = []; - for (let i: number = 0; i < n; ++i) items.push(randint(1, n)); + const items: number[] = []; + for (let i: number = 0; i < n; ++i) items.push(randint(1, n)); - const v: Vector = new Vector(items); - const d: Deque = new Deque(items); + const v: Vector = new Vector(items); + const d: Deque = new Deque(items); - return [ - TimeWatch.measure(() => items.sort((x, y) => x - y)), - TimeWatch.measure(() => sort(v)), - TimeWatch.measure(() => sort(d)), - ]; + return [ + TimeWatch.measure(() => items.sort((x, y) => x - y)), + TimeWatch.measure(() => sort(v)), + TimeWatch.measure(() => sort(d)), + ]; } export async function main(): Promise { - let ret: string = - "## Sorts \n" + - " N | Array | Vector | Deque \n" + - "---|-------|--------|-------\n"; - - for (const n of [1000, 10000, 100000]) { - let line: string = StringUtil.numberFormat(n); - for (const time of watch(n)) - line += ` | ${StringUtil.numberFormat(time)}`; - - ret += line + "\n"; - } - return ret; + let ret: string = + "## Sorts \n" + + " N | Array | Vector | Deque \n" + + "---|-------|--------|-------\n"; + + for (const n of [1000, 10000, 100000]) { + let line: string = StringUtil.numberFormat(n); + for (const time of watch(n)) line += ` | ${StringUtil.numberFormat(time)}`; + + ret += line + "\n"; + } + return ret; } diff --git a/src/container/Deque.ts b/src/container/Deque.ts index 29c615b8..4874cdaf 100644 --- a/src/container/Deque.ts +++ b/src/container/Deque.ts @@ -1,23 +1,21 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ import { IArrayContainer } from "../base/container/IArrayContainer"; +import { InvalidArgument } from "../exception/InvalidArgument"; import { ArrayContainer } from "../internal/container/linear/ArrayContainer"; +import { ErrorGenerator } from "../internal/exception/ErrorGenerator"; +import { Temporary } from "../internal/functional/Temporary"; import { ArrayIterator } from "../internal/iterator/ArrayIterator"; import { ArrayReverseIterator } from "../internal/iterator/ArrayReverseIterator"; - -import { IForwardIterator } from "../iterator/IForwardIterator"; import { NativeArrayIterator } from "../internal/iterator/disposable/NativeArrayIterator"; - -import { Pair } from "../utility/Pair"; -import { InvalidArgument } from "../exception/InvalidArgument"; +import { IForwardIterator } from "../iterator/IForwardIterator"; import { distance } from "../iterator/global"; - -import { ErrorGenerator } from "../internal/exception/ErrorGenerator"; -import { Temporary } from "../internal/functional/Temporary"; +import { Pair } from "../utility/Pair"; /** * Double ended queue. @@ -25,44 +23,39 @@ import { Temporary } from "../internal/functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export class Deque - extends ArrayContainer< - T, - Deque, - Deque, - Deque.Iterator, - Deque.ReverseIterator, - T - > - implements - IArrayContainer< - T, - Deque, - Deque.Iterator, - Deque.ReverseIterator - > + extends ArrayContainer< + T, + Deque, + Deque, + Deque.Iterator, + Deque.ReverseIterator, + T + > + implements + IArrayContainer, Deque.Iterator, Deque.ReverseIterator> { - // A matrix containing elements. - // - // This {@link matrix_} is the biggest difference one between {@link Vector} and {@link Deque}. - // Its number of rows follows {@link ROW_SIZE} and number of columns follows {@link get_col_size} which - // returns divide of {@link capacity} and {@link ROW_SIZE}. - // - // By separating segment of elements (segment: row, elements in a segment: col), {@link Deque} takes - // advantage of time complexity on inserting element in middle position. {@link Deque} is {@link ROW_SIZE} - // times faster than {@link Vector} when inserting elements in middle position. - // - // However, separating segment of elements from matrix, {@link Deque} also takes disadvantage of - // time complexity on accessing element. {@link Deque} is {@link ROW_SIZE} times slower than {@link Vector} - // when accessing element. - private matrix_!: Array>; - - // Number of elements stored in the {@link Deque}. - private size_!: number; - - // Maximum capacity that current {@link matrix_} can store in. - private capacity_!: number; - - /* ========================================================= + // A matrix containing elements. + // + // This {@link matrix_} is the biggest difference one between {@link Vector} and {@link Deque}. + // Its number of rows follows {@link ROW_SIZE} and number of columns follows {@link get_col_size} which + // returns divide of {@link capacity} and {@link ROW_SIZE}. + // + // By separating segment of elements (segment: row, elements in a segment: col), {@link Deque} takes + // advantage of time complexity on inserting element in middle position. {@link Deque} is {@link ROW_SIZE} + // times faster than {@link Vector} when inserting elements in middle position. + // + // However, separating segment of elements from matrix, {@link Deque} also takes disadvantage of + // time complexity on accessing element. {@link Deque} is {@link ROW_SIZE} times slower than {@link Vector} + // when accessing element. + private matrix_!: Array>; + + // Number of elements stored in the {@link Deque}. + private size_!: number; + + // Maximum capacity that current {@link matrix_} can store in. + private capacity_!: number; + + /* ========================================================= CONSTRUCTORS & SEMI-CONSTRUCTORS - CONSTRUCTORS - ASSIGN, RESERVE & CLEAR @@ -70,259 +63,256 @@ export class Deque ============================================================ CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor(); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - */ - public constructor(items: T[]); - - /** - * Copy Constructor - * - * @param obj Object to copy. - */ - public constructor(obj: Deque); - - /** - * Fill Constructor. - * - * @param size Initial size. - * @param val Value to fill. - */ - public constructor(size: number, val: T); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - */ - public constructor( - first: Readonly>, - last: Readonly>, - ); - - public constructor(...args: any[]) { - super(); - - // CONSTRUCTORS BRANCH - if (args.length === 0) { - this.clear(); - } - if (args.length === 1 && args[0] instanceof Array) { - // INITIALIZER CONSTRUCTOR - const array: Array = args[0]; - const first = new NativeArrayIterator(array, 0); - const last = new NativeArrayIterator(array, array.length); - - this.assign(first, last); - } else if (args.length === 1 && args[0] instanceof Deque) { - // COPY CONSTRUCTOR - const container: Deque = args[0]; - this.assign(container.begin(), container.end()); - } else if (args.length === 2) { - // ASSIGN CONSTRUCTOR - this.assign(args[0], args[1]); - } - } - - /* --------------------------------------------------------- + /** + * Default Constructor. + */ + public constructor(); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + */ + public constructor(items: T[]); + + /** + * Copy Constructor + * + * @param obj Object to copy. + */ + public constructor(obj: Deque); + + /** + * Fill Constructor. + * + * @param size Initial size. + * @param val Value to fill. + */ + public constructor(size: number, val: T); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + */ + public constructor( + first: Readonly>, + last: Readonly>, + ); + + public constructor(...args: any[]) { + super(); + + // CONSTRUCTORS BRANCH + if (args.length === 0) { + this.clear(); + } + if (args.length === 1 && args[0] instanceof Array) { + // INITIALIZER CONSTRUCTOR + const array: Array = args[0]; + const first = new NativeArrayIterator(array, 0); + const last = new NativeArrayIterator(array, array.length); + + this.assign(first, last); + } else if (args.length === 1 && args[0] instanceof Deque) { + // COPY CONSTRUCTOR + const container: Deque = args[0]; + this.assign(container.begin(), container.end()); + } else if (args.length === 2) { + // ASSIGN CONSTRUCTOR + this.assign(args[0], args[1]); + } + } + + /* --------------------------------------------------------- ASSIGN, RESERVE & CLEAR --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public assign(n: number, val: T): void; - - /** - * @inheritDoc - */ - public assign< - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void; - - public assign(first: any, second: any): void { - // CLEAR PREVIOUS CONTENTS - this.clear(); - - // INSERT ITEMS - this.insert(this.end(), first, second); - } - - /** - * @inheritDoc - */ - public clear(): void { - // CLEAR CONTENTS - this.matrix_ = [[]]; - - // RE-INDEX - this.size_ = 0; - this.capacity_ = Deque.MIN_CAPACITY; - } - - /** - * @inheritDoc - */ - public resize(n: number): void { - n = Deque._Emend(n, "resize"); - - const expansion: number = n - this.size(); - if (expansion > 0) this.insert(this.end(), expansion, undefined!); - else if (expansion < 0) - this.erase(this.end().advance(-expansion), this.end()); - } - - /** - * Reserve {@link capacity} enable to store *n* elements. - * - * @param n The capacity to reserve. - */ - public reserve(n: number): void { - this._Reserve(Deque._Emend(n, "reserve")); - } - - private _Reserve(n: number): void { - // NEW MEMBERS TO BE ASSSIGNED - const matrix: T[][] = [[]]; - const length: number = this._Compute_col_size(n); - - //-------- - // RE-FILL - //-------- - for (let r: number = 0; r < this.matrix_.length; ++r) { - const row: T[] = this.matrix_[r]; - - for (let c: number = 0; c < row.length; ++c) { - let new_row: T[] = matrix[matrix.length - 1]; - if ( - matrix.length < Deque.ROW_SIZE && - new_row.length === length - ) { - new_row = []; - matrix.push(new_row); - } - new_row.push(row[c]); - } + /** + * @inheritDoc + */ + public assign(n: number, val: T): void; + + /** + * @inheritDoc + */ + public assign< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void; + + public assign(first: any, second: any): void { + // CLEAR PREVIOUS CONTENTS + this.clear(); + + // INSERT ITEMS + this.insert(this.end(), first, second); + } + + /** + * @inheritDoc + */ + public clear(): void { + // CLEAR CONTENTS + this.matrix_ = [[]]; + + // RE-INDEX + this.size_ = 0; + this.capacity_ = Deque.MIN_CAPACITY; + } + + /** + * @inheritDoc + */ + public resize(n: number): void { + n = Deque._Emend(n, "resize"); + + const expansion: number = n - this.size(); + if (expansion > 0) this.insert(this.end(), expansion, undefined!); + else if (expansion < 0) + this.erase(this.end().advance(-expansion), this.end()); + } + + /** + * Reserve {@link capacity} enable to store *n* elements. + * + * @param n The capacity to reserve. + */ + public reserve(n: number): void { + this._Reserve(Deque._Emend(n, "reserve")); + } + + private _Reserve(n: number): void { + // NEW MEMBERS TO BE ASSSIGNED + const matrix: T[][] = [[]]; + const length: number = this._Compute_col_size(n); + + //-------- + // RE-FILL + //-------- + for (let r: number = 0; r < this.matrix_.length; ++r) { + const row: T[] = this.matrix_[r]; + + for (let c: number = 0; c < row.length; ++c) { + let new_row: T[] = matrix[matrix.length - 1]; + if (matrix.length < Deque.ROW_SIZE && new_row.length === length) { + new_row = []; + matrix.push(new_row); } - - // ASSIGN MEMBERS - this.matrix_ = matrix; - this.capacity_ = n; - } - - /** - * Shrink {@link capacity} to actual {@link size}. - */ - public shrink_to_fit(): void { - this._Reserve(this.size()); - } - - /** - * @inheritDoc - */ - public swap(obj: Deque): void { - this._Swap(obj); - } - - private _Swap(obj: Deque): void { - // SWAP CONTENTS - [this.matrix_, obj.matrix_] = [obj.matrix_, this.matrix_]; - [this.size_, obj.size_] = [obj.size_, this.size_]; - [this.capacity_, obj.capacity_] = [obj.capacity_, this.capacity_]; - } - - private static _Emend(n: number, method: string): number { - n = Math.floor(n); - if (n <= 0) - throw new InvalidArgument( - `Error on Deque.${method}(): n must be positive integer -> (n = ${n})`, - ); - - return n; - } - - /* ========================================================= + new_row.push(row[c]); + } + } + + // ASSIGN MEMBERS + this.matrix_ = matrix; + this.capacity_ = n; + } + + /** + * Shrink {@link capacity} to actual {@link size}. + */ + public shrink_to_fit(): void { + this._Reserve(this.size()); + } + + /** + * @inheritDoc + */ + public swap(obj: Deque): void { + this._Swap(obj); + } + + private _Swap(obj: Deque): void { + // SWAP CONTENTS + [this.matrix_, obj.matrix_] = [obj.matrix_, this.matrix_]; + [this.size_, obj.size_] = [obj.size_, this.size_]; + [this.capacity_, obj.capacity_] = [obj.capacity_, this.capacity_]; + } + + private static _Emend(n: number, method: string): number { + n = Math.floor(n); + if (n <= 0) + throw new InvalidArgument( + `Error on Deque.${method}(): n must be positive integer -> (n = ${n})`, + ); + + return n; + } + + /* ========================================================= ACCESSORS - BASIC ELEMENTS - INDEX ACCESSORS ============================================================ BASIC ELEMENTS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public size(): number { - return this.size_; - } - - /** - * The capacity to store elements. - * - * @return The capacity. - */ - public capacity(): number { - return this.capacity_; - } - - /** - * @inheritDoc - */ - public nth(index: number): Deque.Iterator { - return new Deque.Iterator(this as Deque, index); - } - - /** - * @inheritDoc - */ - public [Symbol.iterator](): IterableIterator { - return new Deque.ForOfAdaptor(this.matrix_); - } - - protected source(): Deque { - return this; - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public size(): number { + return this.size_; + } + + /** + * The capacity to store elements. + * + * @return The capacity. + */ + public capacity(): number { + return this.capacity_; + } + + /** + * @inheritDoc + */ + public nth(index: number): Deque.Iterator { + return new Deque.Iterator(this as Deque, index); + } + + /** + * @inheritDoc + */ + public [Symbol.iterator](): IterableIterator { + return new Deque.ForOfAdaptor(this.matrix_); + } + + protected source(): Deque { + return this; + } + + /* --------------------------------------------------------- INDEX ACCESSORS --------------------------------------------------------- */ - protected _At(index: number): T { - const indexPair: Pair = this._Fetch_index(index); - return this.matrix_[indexPair.first][indexPair.second]; - } + protected _At(index: number): T { + const indexPair: Pair = this._Fetch_index(index); + return this.matrix_[indexPair.first][indexPair.second]; + } - protected _Set(index: number, val: T): void { - const indexPair: Pair = this._Fetch_index(index); - this.matrix_[indexPair.first][indexPair.second] = val; - } + protected _Set(index: number, val: T): void { + const indexPair: Pair = this._Fetch_index(index); + this.matrix_[indexPair.first][indexPair.second] = val; + } - private _Fetch_index(index: number): Pair { - // Fetch row and column's index. - let row: number; - for (row = 0; row < this.matrix_.length; row++) { - const array: Array = this.matrix_[row]; - if (index < array.length) break; + private _Fetch_index(index: number): Pair { + // Fetch row and column's index. + let row: number; + for (row = 0; row < this.matrix_.length; row++) { + const array: Array = this.matrix_[row]; + if (index < array.length) break; - index -= array.length; - } + index -= array.length; + } - if (row === this.matrix_.length) row--; + if (row === this.matrix_.length) row--; - return new Pair(row, index); - } + return new Pair(row, index); + } - private _Compute_col_size(capacity = this.capacity_): number { - // Get column size; {@link capacity_ capacity} / {@link ROW_SIZE row}. - return Math.floor(capacity / Deque.ROW_SIZE); - } + private _Compute_col_size(capacity = this.capacity_): number { + // Get column size; {@link capacity_ capacity} / {@link ROW_SIZE row}. + return Math.floor(capacity / Deque.ROW_SIZE); + } - /* ========================================================= + /* ========================================================= ELEMENTS I/O - PUSH & POP - INSERT @@ -330,375 +320,359 @@ export class Deque ============================================================ PUSH & POP --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public push(...items: T[]): number { - if (items.length === 0) return this.size(); - - // INSERT BY RANGE - const first: NativeArrayIterator = new NativeArrayIterator(items, 0); - const last: NativeArrayIterator = new NativeArrayIterator( - items, - items.length, - ); - - this._Insert_by_range(this.end(), first, last); - - // RETURN SIZE - return this.size(); - } - - /** - * @inheritDoc - */ - public push_front(val: T): void { - // ADD CAPACITY & ROW - this._Try_expand_capacity(this.size_ + 1); - this._Try_add_row_at_front(); - - // INSERT VALUE - this.matrix_[0].unshift(val); - ++this.size_; - } - - /** - * @inheritDoc - */ - public push_back(val: T): void { - // ADD CAPACITY & ROW - this._Try_expand_capacity(this.size_ + 1); - this._Try_add_row_at_back(); - - // INSERT VALUE - this.matrix_[this.matrix_.length - 1].push(val); - ++this.size_; - } - - /** - * @inheritDoc - */ - public pop_front(): void { - if (this.empty() === true) - throw ErrorGenerator.empty(this.constructor, "pop_front"); - - // EREASE FIRST ELEMENT - this.matrix_[0].shift(); - if (this.matrix_[0].length === 0 && this.matrix_.length > 1) - this.matrix_.shift(); - - // SHRINK SIZE - this.size_--; - } - - protected _Pop_back(): void { - // ERASE LAST ELEMENT - const lastArray: Array = this.matrix_[this.matrix_.length - 1]; - lastArray.pop(); - - if (lastArray.length === 0 && this.matrix_.length > 1) - this.matrix_.pop(); - - // SHRINK SIZE - this.size_--; - } + /** + * @inheritDoc + */ + public push(...items: T[]): number { + if (items.length === 0) return this.size(); + + // INSERT BY RANGE + const first: NativeArrayIterator = new NativeArrayIterator(items, 0); + const last: NativeArrayIterator = new NativeArrayIterator( + items, + items.length, + ); - /* --------------------------------------------------------- + this._Insert_by_range(this.end(), first, last); + + // RETURN SIZE + return this.size(); + } + + /** + * @inheritDoc + */ + public push_front(val: T): void { + // ADD CAPACITY & ROW + this._Try_expand_capacity(this.size_ + 1); + this._Try_add_row_at_front(); + + // INSERT VALUE + this.matrix_[0].unshift(val); + ++this.size_; + } + + /** + * @inheritDoc + */ + public push_back(val: T): void { + // ADD CAPACITY & ROW + this._Try_expand_capacity(this.size_ + 1); + this._Try_add_row_at_back(); + + // INSERT VALUE + this.matrix_[this.matrix_.length - 1].push(val); + ++this.size_; + } + + /** + * @inheritDoc + */ + public pop_front(): void { + if (this.empty() === true) + throw ErrorGenerator.empty(this.constructor, "pop_front"); + + // EREASE FIRST ELEMENT + this.matrix_[0].shift(); + if (this.matrix_[0].length === 0 && this.matrix_.length > 1) + this.matrix_.shift(); + + // SHRINK SIZE + this.size_--; + } + + protected _Pop_back(): void { + // ERASE LAST ELEMENT + const lastArray: Array = this.matrix_[this.matrix_.length - 1]; + lastArray.pop(); + + if (lastArray.length === 0 && this.matrix_.length > 1) this.matrix_.pop(); + + // SHRINK SIZE + this.size_--; + } + + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - protected _Insert_by_range< - InputIterator extends Readonly>, - >( - pos: Deque.Iterator, - first: InputIterator, - last: InputIterator, - ): Deque.Iterator { - const size: number = this.size_ + distance(first, last); - if (size === this.size_) - // FIRST === LAST - return pos; - - if (pos.equals(this.end()) === true) { - // EXPAND CAPACITY IF REQUIRED - this._Try_expand_capacity(size); - - // INSERT TO END - this._Insert_to_end(first, last); - - // CHANGE POS TO RETURN - pos = this.nth(this.size_); - } else { - // INSERT ITEMS IN THE MIDDLE - if (size > this.capacity_) { - // A TEMPORARY DEQUE - const deque: Deque = new Deque(); - deque._Reserve( - Math.max( - size, - Math.floor(this.capacity_ * Deque.MAGNIFIER), - ), - ); - - // INSERT ITEM SEQUENTIALLY - deque._Insert_to_end(this.begin(), pos); - deque._Insert_to_end(first, last); - deque._Insert_to_end(pos, this.end()); - - // AND SWAP THIS WITH THE TEMP - this._Swap(deque); - } else this._Insert_to_middle(pos, first, last); - } - - this.size_ = size; - return pos; - } - - private _Insert_to_middle< - InputIterator extends Readonly>, - >(pos: Deque.Iterator, first: InputIterator, last: InputIterator): void { - const col_size: number = this._Compute_col_size(); - - // POSITION OF MATRIX - const indexes: Pair = this._Fetch_index(pos.index()); - let row: Array = this.matrix_[indexes.first]; - const col: number = indexes.second; - - // MOVE BACK SIDE TO TEMPORARY ARRAY - const back_items: Array = row.splice(col); - - // INSERT ITEMS - for (; !first.equals(last); first = first.next()) { - if ( - row.length === col_size && - this.matrix_.length < Deque.ROW_SIZE - ) { - row = new Array(); - - const spliced_array: T[][] = this.matrix_.splice( - ++indexes.first, - ); - this.matrix_.push(row); - this.matrix_.push(...spliced_array); - } - row.push(first.value); - } - - // INSERT ITEMS IN THE BACK SIDE - for (let i: number = 0; i < back_items.length; ++i) { - if ( - row.length === col_size && - this.matrix_.length < Deque.ROW_SIZE - ) { - row = new Array(); - - const spliced_array: T[][] = this.matrix_.splice( - ++indexes.first, - ); - this.matrix_.push(row); - this.matrix_.push(...spliced_array); - } - row.push(back_items[i]); - } - } - - private _Insert_to_end< - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void { - // INSERT ITEMS IN THE BACK - for (; !first.equals(last); first = first.next()) { - // ADD ROW IF REQUIRED - this._Try_add_row_at_back(); - - // INSERT VALUE - this.matrix_[this.matrix_.length - 1].push(first.value); - } - } - - private _Try_expand_capacity(size: number): boolean { - if (size <= this.capacity_) return false; - - // MAX (CAPACITY * 1.5, TARGET SIZE) - size = Math.max(size, Math.floor(this.capacity_ * Deque.MAGNIFIER)); - this._Reserve(size); - - return true; - } - - private _Try_add_row_at_front(): boolean { - const col_size: number = this._Compute_col_size(); - - if ( - this.matrix_[0].length >= col_size && - this.matrix_.length < Deque.ROW_SIZE - ) { - this.matrix_ = ([[]] as T[][]).concat(...this.matrix_); - return true; - } else return false; - } - - private _Try_add_row_at_back(): boolean { - const col_size: number = this._Compute_col_size(); - - if ( - this.matrix_[this.matrix_.length - 1].length >= col_size && - this.matrix_.length < Deque.ROW_SIZE - ) { - this.matrix_.push([]); - return true; - } else return false; - } + protected _Insert_by_range< + InputIterator extends Readonly>, + >( + pos: Deque.Iterator, + first: InputIterator, + last: InputIterator, + ): Deque.Iterator { + const size: number = this.size_ + distance(first, last); + if (size === this.size_) + // FIRST === LAST + return pos; + + if (pos.equals(this.end()) === true) { + // EXPAND CAPACITY IF REQUIRED + this._Try_expand_capacity(size); + + // INSERT TO END + this._Insert_to_end(first, last); + + // CHANGE POS TO RETURN + pos = this.nth(this.size_); + } else { + // INSERT ITEMS IN THE MIDDLE + if (size > this.capacity_) { + // A TEMPORARY DEQUE + const deque: Deque = new Deque(); + deque._Reserve( + Math.max(size, Math.floor(this.capacity_ * Deque.MAGNIFIER)), + ); - /* --------------------------------------------------------- + // INSERT ITEM SEQUENTIALLY + deque._Insert_to_end(this.begin(), pos); + deque._Insert_to_end(first, last); + deque._Insert_to_end(pos, this.end()); + + // AND SWAP THIS WITH THE TEMP + this._Swap(deque); + } else this._Insert_to_middle(pos, first, last); + } + + this.size_ = size; + return pos; + } + + private _Insert_to_middle< + InputIterator extends Readonly>, + >(pos: Deque.Iterator, first: InputIterator, last: InputIterator): void { + const col_size: number = this._Compute_col_size(); + + // POSITION OF MATRIX + const indexes: Pair = this._Fetch_index(pos.index()); + let row: Array = this.matrix_[indexes.first]; + const col: number = indexes.second; + + // MOVE BACK SIDE TO TEMPORARY ARRAY + const back_items: Array = row.splice(col); + + // INSERT ITEMS + for (; !first.equals(last); first = first.next()) { + if (row.length === col_size && this.matrix_.length < Deque.ROW_SIZE) { + row = new Array(); + + const spliced_array: T[][] = this.matrix_.splice(++indexes.first); + this.matrix_.push(row); + this.matrix_.push(...spliced_array); + } + row.push(first.value); + } + + // INSERT ITEMS IN THE BACK SIDE + for (let i: number = 0; i < back_items.length; ++i) { + if (row.length === col_size && this.matrix_.length < Deque.ROW_SIZE) { + row = new Array(); + + const spliced_array: T[][] = this.matrix_.splice(++indexes.first); + this.matrix_.push(row); + this.matrix_.push(...spliced_array); + } + row.push(back_items[i]); + } + } + + private _Insert_to_end< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void { + // INSERT ITEMS IN THE BACK + for (; !first.equals(last); first = first.next()) { + // ADD ROW IF REQUIRED + this._Try_add_row_at_back(); + + // INSERT VALUE + this.matrix_[this.matrix_.length - 1].push(first.value); + } + } + + private _Try_expand_capacity(size: number): boolean { + if (size <= this.capacity_) return false; + + // MAX (CAPACITY * 1.5, TARGET SIZE) + size = Math.max(size, Math.floor(this.capacity_ * Deque.MAGNIFIER)); + this._Reserve(size); + + return true; + } + + private _Try_add_row_at_front(): boolean { + const col_size: number = this._Compute_col_size(); + + if ( + this.matrix_[0].length >= col_size && + this.matrix_.length < Deque.ROW_SIZE + ) { + this.matrix_ = ([[]] as T[][]).concat(...this.matrix_); + return true; + } else return false; + } + + private _Try_add_row_at_back(): boolean { + const col_size: number = this._Compute_col_size(); + + if ( + this.matrix_[this.matrix_.length - 1].length >= col_size && + this.matrix_.length < Deque.ROW_SIZE + ) { + this.matrix_.push([]); + return true; + } else return false; + } + + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - protected _Erase_by_range( - first: Deque.Iterator, - last: Deque.Iterator, - ): Deque.Iterator { - if (first.index() >= this.size()) return first; - - // INDEXING - let size: number; - if (last.index() >= this.size()) - // LAST IS END() - size = this.size() - first.index(); - // LAST IS NOT END() - else size = last.index() - first.index(); - - this.size_ -= size; - - // ERASING - let first_row: T[] = null!; - let second_row: T[] = null!; - let i: number = 0; - - while (size !== 0) { - // FIND MATCHED ROW AND COLUMN - const indexes: Pair = this._Fetch_index( - first.index(), - ); - const row: Array = this.matrix_[indexes.first]; - const col: number = indexes.second; - - // EARSE FROM THE ROW - const my_delete_size: number = Math.min(size, row.length - col); - row.splice(col, my_delete_size); - - // TO MERGE - if (row.length !== 0) - if (i === 0) first_row = row; - else second_row = row; - - // ERASE THE ENTIRE ROW IF REQUIRED - if (row.length === 0 && this.matrix_.length > 1) - this.matrix_.splice(indexes.first, 1); - - // TO THE NEXT STEP - size -= my_delete_size; - ++i; - } - - // MERGE FIRST AND SECOND ROW - if ( - first_row !== null && - second_row !== null && - first_row.length + second_row.length <= this._Compute_col_size() - ) { - first_row.push(...second_row); - this.matrix_.splice(this.matrix_.indexOf(second_row), 1); - } - - return first; - } + protected _Erase_by_range( + first: Deque.Iterator, + last: Deque.Iterator, + ): Deque.Iterator { + if (first.index() >= this.size()) return first; + + // INDEXING + let size: number; + if (last.index() >= this.size()) + // LAST IS END() + size = this.size() - first.index(); + // LAST IS NOT END() + else size = last.index() - first.index(); + + this.size_ -= size; + + // ERASING + let first_row: T[] = null!; + let second_row: T[] = null!; + let i: number = 0; + + while (size !== 0) { + // FIND MATCHED ROW AND COLUMN + const indexes: Pair = this._Fetch_index(first.index()); + const row: Array = this.matrix_[indexes.first]; + const col: number = indexes.second; + + // EARSE FROM THE ROW + const my_delete_size: number = Math.min(size, row.length - col); + row.splice(col, my_delete_size); + + // TO MERGE + if (row.length !== 0) + if (i === 0) first_row = row; + else second_row = row; + + // ERASE THE ENTIRE ROW IF REQUIRED + if (row.length === 0 && this.matrix_.length > 1) + this.matrix_.splice(indexes.first, 1); + + // TO THE NEXT STEP + size -= my_delete_size; + ++i; + } + + // MERGE FIRST AND SECOND ROW + if ( + first_row !== null && + second_row !== null && + first_row.length + second_row.length <= this._Compute_col_size() + ) { + first_row.push(...second_row); + this.matrix_.splice(this.matrix_.indexOf(second_row), 1); + } + + return first; + } } /** * */ export namespace Deque { - //---- - // ITERATORS - //---- - // HEAD - /** - * Iterator of {@link Deque} - */ - export type Iterator = ArrayIterator>; - - /** - * Reverse iterator of {@link Deque} - */ - export type ReverseIterator = ArrayReverseIterator>; - - // BODY - export const Iterator = ArrayIterator; - export const ReverseIterator = ArrayReverseIterator; - - //---- - // CONSTANTS - //---- - /** - * Row size of the {@link Deque.matrix_ matrix} which contains elements. - * - * Note that the {@link ROW_SIZE} affects on time complexity of accessing and inserting element. - * Accessing element is {@link ROW_SIZE} times slower than ordinary {@link Vector} and inserting element - * in middle position is {@link ROW_SIZE} times faster than ordinary {@link Vector}. - * - * When the {@link ROW_SIZE} returns 8, time complexity of accessing element is O(8) and inserting - * element in middle position is O(N/8). ({@link Vector}'s time complexity of accessement is O(1) - * and inserting element is O(N)). - */ - export const ROW_SIZE = 8; - - /** - * Minimum {@link Deque.capacity}. - * - * Although a {@link Deque} has few elements, even no element is belonged to, the {@link Deque} - * keeps the minimum {@link Deque.capacity} at least. - */ - export const MIN_CAPACITY = 36; - - /** - * Expansion ratio. - */ - export const MAGNIFIER = 1.5; - - /** - * @internal - */ - export class ForOfAdaptor implements IterableIterator { - private matrix_: T[][]; - private row_: number; - private col_: number; - - public constructor(matrix: T[][]) { - this.matrix_ = matrix; - this.row_ = 0; - this.col_ = 0; + //---- + // ITERATORS + //---- + // HEAD + /** + * Iterator of {@link Deque} + */ + export type Iterator = ArrayIterator>; + + /** + * Reverse iterator of {@link Deque} + */ + export type ReverseIterator = ArrayReverseIterator>; + + // BODY + export const Iterator = ArrayIterator; + export const ReverseIterator = ArrayReverseIterator; + + //---- + // CONSTANTS + //---- + /** + * Row size of the {@link Deque.matrix_ matrix} which contains elements. + * + * Note that the {@link ROW_SIZE} affects on time complexity of accessing and inserting element. + * Accessing element is {@link ROW_SIZE} times slower than ordinary {@link Vector} and inserting element + * in middle position is {@link ROW_SIZE} times faster than ordinary {@link Vector}. + * + * When the {@link ROW_SIZE} returns 8, time complexity of accessing element is O(8) and inserting + * element in middle position is O(N/8). ({@link Vector}'s time complexity of accessement is O(1) + * and inserting element is O(N)). + */ + export const ROW_SIZE = 8; + + /** + * Minimum {@link Deque.capacity}. + * + * Although a {@link Deque} has few elements, even no element is belonged to, the {@link Deque} + * keeps the minimum {@link Deque.capacity} at least. + */ + export const MIN_CAPACITY = 36; + + /** + * Expansion ratio. + */ + export const MAGNIFIER = 1.5; + + /** + * @internal + */ + export class ForOfAdaptor implements IterableIterator { + private matrix_: T[][]; + private row_: number; + private col_: number; + + public constructor(matrix: T[][]) { + this.matrix_ = matrix; + this.row_ = 0; + this.col_ = 0; + } + + public next(): IteratorResult { + if (this.row_ === this.matrix_.length) + return { + done: true, + value: undefined!, + }; + else { + const val: T = this.matrix_[this.row_][this.col_]; + if (++this.col_ === this.matrix_[this.row_].length) { + ++this.row_; + this.col_ = 0; } - public next(): IteratorResult { - if (this.row_ === this.matrix_.length) - return { - done: true, - value: undefined!, - }; - else { - const val: T = this.matrix_[this.row_][this.col_]; - if (++this.col_ === this.matrix_[this.row_].length) { - ++this.row_; - this.col_ = 0; - } - - return { - done: false, - value: val, - }; - } - } + return { + done: false, + value: val, + }; + } + } - public [Symbol.iterator](): IterableIterator { - return this; - } + public [Symbol.iterator](): IterableIterator { + return this; } + } } diff --git a/src/container/ForwardList.ts b/src/container/ForwardList.ts index e04db91a..fb468b31 100644 --- a/src/container/ForwardList.ts +++ b/src/container/ForwardList.ts @@ -1,32 +1,29 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IForwardContainer } from "../ranges/container/IForwardContainer"; -import { IForwardIterator } from "../iterator/IForwardIterator"; +import { sort as sort_func } from "../algorithm/sorting"; import { IPointer } from "../functional/IPointer"; - +import { equal_to, less } from "../functional/comparators"; +import { IListAlgorithm } from "../internal/container/linear/IListAlgorithm"; import { IClear } from "../internal/container/partial/IClear"; -import { IEmpty } from "../internal/container/partial/IEmpty"; -import { ISize } from "../internal/container/partial/ISize"; import { IDeque } from "../internal/container/partial/IDeque"; +import { IEmpty } from "../internal/container/partial/IEmpty"; import { IFront } from "../internal/container/partial/IFront"; -import { IListAlgorithm } from "../internal/container/linear/IListAlgorithm"; - -import { Repeater } from "../internal/iterator/disposable/Repeater"; -import { ForOfAdaptor } from "../internal/iterator/disposable/ForOfAdaptor"; -import { Vector } from "./Vector"; +import { ISize } from "../internal/container/partial/ISize"; import { ErrorGenerator } from "../internal/exception/ErrorGenerator"; - -import { Comparator } from "../internal/functional/Comparator"; import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; +import { Comparator } from "../internal/functional/Comparator"; import { UnaryPredicator } from "../internal/functional/UnaryPredicator"; - +import { ForOfAdaptor } from "../internal/iterator/disposable/ForOfAdaptor"; +import { Repeater } from "../internal/iterator/disposable/Repeater"; +import { IForwardIterator } from "../iterator/IForwardIterator"; import { advance, distance } from "../iterator/global"; -import { equal_to, less } from "../functional/comparators"; -import { sort as sort_func } from "../algorithm/sorting"; +import { IForwardContainer } from "../ranges/container/IForwardContainer"; +import { Vector } from "./Vector"; /** * Singly Linked List. @@ -34,342 +31,337 @@ import { sort as sort_func } from "../algorithm/sorting"; * @author Jeongho Nam - https://github.com/samchon */ export class ForwardList - implements - IForwardContainer>, - IClear, - IEmpty, - ISize, - IDeque, - IFront, - Iterable, - IListAlgorithm> + implements + IForwardContainer>, + IClear, + IEmpty, + ISize, + IDeque, + IFront, + Iterable, + IListAlgorithm> { - private ptr_: IPointer>; - private size_: number; + private ptr_: IPointer>; + private size_: number; - private before_begin_: ForwardList.Iterator; - private end_: ForwardList.Iterator; + private before_begin_: ForwardList.Iterator; + private end_: ForwardList.Iterator; - /* =============================================================== + /* =============================================================== CONSTRUCTORS & SEMI-CONSTRUCTORS - CONSTRUCTORS - ASSIGN & CLEAR ================================================================== CONSTURCTORS --------------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor(); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - */ - public constructor(items: T[]); - - /** - * Copy Constructor - * - * @param obj Object to copy. - */ - public constructor(obj: ForwardList); - - /** - * Fill Constructor. - * - * @param size Initial size. - * @param val Value to fill. - */ - public constructor(n: number, val: T); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - */ - public constructor( - first: Readonly>, - last: Readonly>, - ); - - public constructor(...args: any[]) { - this.ptr_ = { value: this }; - - this.end_ = ForwardList.Iterator.create(this.ptr_, null!); - this.before_begin_ = ForwardList.Iterator.create(this.ptr_, this.end_); - this.size_ = 0; - - if (args.length === 1 && args[0] instanceof Array) { - const array: Array = args[0]; - let it = this.before_begin(); - - for (const val of array) it = this.insert_after(it, val); - } else if (args.length === 1 && args[0] instanceof ForwardList) { - this.assign(args[0].begin(), args[0].end()); - } else if (args.length === 2) this.assign(args[0], args[1]); - } - - /* --------------------------------------------------------------- + /** + * Default Constructor. + */ + public constructor(); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + */ + public constructor(items: T[]); + + /** + * Copy Constructor + * + * @param obj Object to copy. + */ + public constructor(obj: ForwardList); + + /** + * Fill Constructor. + * + * @param size Initial size. + * @param val Value to fill. + */ + public constructor(n: number, val: T); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + */ + public constructor( + first: Readonly>, + last: Readonly>, + ); + + public constructor(...args: any[]) { + this.ptr_ = { value: this }; + + this.end_ = ForwardList.Iterator.create(this.ptr_, null!); + this.before_begin_ = ForwardList.Iterator.create(this.ptr_, this.end_); + this.size_ = 0; + + if (args.length === 1 && args[0] instanceof Array) { + const array: Array = args[0]; + let it = this.before_begin(); + + for (const val of array) it = this.insert_after(it, val); + } else if (args.length === 1 && args[0] instanceof ForwardList) { + this.assign(args[0].begin(), args[0].end()); + } else if (args.length === 2) this.assign(args[0], args[1]); + } + + /* --------------------------------------------------------------- ASSIGN & CLEAR --------------------------------------------------------------- */ - /** - * Fill Assigner. - * - * @param n Initial size. - * @param val Value to fill. - */ - public assign(n: number, val: T): void; - - /** - * Range Assigner. - * - * @param first Input iteartor of the first position. - * @param last Input iterator of the last position. - */ - public assign< - T, - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void; - - public assign(first: any, last: any): void { - this.clear(); - this.insert_after(this.before_begin_, first, last); - } - - /** - * @inheritDoc - */ - public clear(): void { - ForwardList.Iterator._Set_next(this.before_begin_, this.end_); - this.size_ = 0; - } - - /* =============================================================== + /** + * Fill Assigner. + * + * @param n Initial size. + * @param val Value to fill. + */ + public assign(n: number, val: T): void; + + /** + * Range Assigner. + * + * @param first Input iteartor of the first position. + * @param last Input iterator of the last position. + */ + public assign< + T, + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void; + + public assign(first: any, last: any): void { + this.clear(); + this.insert_after(this.before_begin_, first, last); + } + + /** + * @inheritDoc + */ + public clear(): void { + ForwardList.Iterator._Set_next(this.before_begin_, this.end_); + this.size_ = 0; + } + + /* =============================================================== ACCESSORS =============================================================== */ - /** - * @inheritDoc - */ - public size(): number { - return this.size_; - } - - /** - * @inheritDoc - */ - public empty(): boolean { - return this.size_ === 0; - } - - /** - * @inheritDoc - */ - public front(): T; - - /** - * @inheritDoc - */ - public front(val: T): void; - - public front(val?: T): T | void { - const it: ForwardList.Iterator = this.begin(); - - if (arguments.length === 0) return it.value; - else it.value = val!; - } - - /** - * Iterator to before beginning. - * - * @return Iterator to the before beginning. - */ - public before_begin(): ForwardList.Iterator { - return this.before_begin_; - } - - /** - * @inheritDoc - */ - public begin(): ForwardList.Iterator { - return this.before_begin_.next(); - } - - /** - * @inheritDoc - */ - public end(): ForwardList.Iterator { - return this.end_; - } - - /** - * @inheritDoc - */ - public [Symbol.iterator](): IterableIterator { - return new ForOfAdaptor(this.begin(), this.end()); - } - - /* =============================================================== + /** + * @inheritDoc + */ + public size(): number { + return this.size_; + } + + /** + * @inheritDoc + */ + public empty(): boolean { + return this.size_ === 0; + } + + /** + * @inheritDoc + */ + public front(): T; + + /** + * @inheritDoc + */ + public front(val: T): void; + + public front(val?: T): T | void { + const it: ForwardList.Iterator = this.begin(); + + if (arguments.length === 0) return it.value; + else it.value = val!; + } + + /** + * Iterator to before beginning. + * + * @return Iterator to the before beginning. + */ + public before_begin(): ForwardList.Iterator { + return this.before_begin_; + } + + /** + * @inheritDoc + */ + public begin(): ForwardList.Iterator { + return this.before_begin_.next(); + } + + /** + * @inheritDoc + */ + public end(): ForwardList.Iterator { + return this.end_; + } + + /** + * @inheritDoc + */ + public [Symbol.iterator](): IterableIterator { + return new ForOfAdaptor(this.begin(), this.end()); + } + + /* =============================================================== ELEMENTS I/O - INSERT - ERASE ================================================================== INSERT --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public push_front(val: T): void { - this.insert_after(this.before_begin_, val); - } - - /** - * Insert an element. - * - * @param pos Position to insert after. - * @param val Value to insert. - * @return An iterator to the newly inserted element. - */ - public insert_after( - pos: ForwardList.Iterator, - val: T, - ): ForwardList.Iterator; - - /** - * Inserted repeated elements. - * - * @param pos Position to insert after. - * @param n Number of elements to insert. - * @param val Value to insert repeatedly. - * @return An iterator to the last of the newly inserted elements. - */ - public insert_after( - pos: ForwardList.Iterator, - n: number, - val: T, - ): ForwardList.Iterator; - - /** - * Insert range elements. - * - * @param pos Position to insert after. - * @param first Input iterator of the first position. - * @param last Input iteartor of the last position. - * @return An iterator to the last of the newly inserted elements. - */ - public insert_after< - T, - InputIterator extends Readonly>, - >( - pos: ForwardList.Iterator, - first: InputIterator, - last: InputIterator, - ): ForwardList.Iterator; - - public insert_after( - pos: ForwardList.Iterator, - ...args: any[] - ): ForwardList.Iterator { - let ret: ForwardList.Iterator; - - // BRANCHES - if (args.length === 1) - ret = this._Insert_by_repeating_val(pos, 1, args[0]); - else if (typeof args[0] === "number") - ret = this._Insert_by_repeating_val(pos, args[0], args[1]); - else ret = this._Insert_by_range(pos, args[0], args[1]); - - // RETURNS - return ret; + /** + * @inheritDoc + */ + public push_front(val: T): void { + this.insert_after(this.before_begin_, val); + } + + /** + * Insert an element. + * + * @param pos Position to insert after. + * @param val Value to insert. + * @return An iterator to the newly inserted element. + */ + public insert_after( + pos: ForwardList.Iterator, + val: T, + ): ForwardList.Iterator; + + /** + * Inserted repeated elements. + * + * @param pos Position to insert after. + * @param n Number of elements to insert. + * @param val Value to insert repeatedly. + * @return An iterator to the last of the newly inserted elements. + */ + public insert_after( + pos: ForwardList.Iterator, + n: number, + val: T, + ): ForwardList.Iterator; + + /** + * Insert range elements. + * + * @param pos Position to insert after. + * @param first Input iterator of the first position. + * @param last Input iteartor of the last position. + * @return An iterator to the last of the newly inserted elements. + */ + public insert_after< + T, + InputIterator extends Readonly>, + >( + pos: ForwardList.Iterator, + first: InputIterator, + last: InputIterator, + ): ForwardList.Iterator; + + public insert_after( + pos: ForwardList.Iterator, + ...args: any[] + ): ForwardList.Iterator { + let ret: ForwardList.Iterator; + + // BRANCHES + if (args.length === 1) ret = this._Insert_by_repeating_val(pos, 1, args[0]); + else if (typeof args[0] === "number") + ret = this._Insert_by_repeating_val(pos, args[0], args[1]); + else ret = this._Insert_by_range(pos, args[0], args[1]); + + // RETURNS + return ret; + } + + private _Insert_by_repeating_val( + pos: ForwardList.Iterator, + n: number, + val: T, + ): ForwardList.Iterator { + const first: Repeater = new Repeater(0, val); + const last: Repeater = new Repeater(n); + + return this._Insert_by_range(pos, first, last); + } + + private _Insert_by_range< + InputIterator extends Readonly>, + >( + pos: ForwardList.Iterator, + first: InputIterator, + last: InputIterator, + ): ForwardList.Iterator { + const nodes: ForwardList.Iterator[] = []; + let count: number = 0; + + for (; !first.equals(last); first = first.next()) { + const node = ForwardList.Iterator.create(this.ptr_, null!, first.value); + nodes.push(node); + + ++count; } + if (count === 0) return pos; - private _Insert_by_repeating_val( - pos: ForwardList.Iterator, - n: number, - val: T, - ): ForwardList.Iterator { - const first: Repeater = new Repeater(0, val); - const last: Repeater = new Repeater(n); + for (let i: number = 0; i < count - 1; ++i) + ForwardList.Iterator._Set_next(nodes[i], nodes[i + 1]); + ForwardList.Iterator._Set_next(nodes[nodes.length - 1], pos.next()); + ForwardList.Iterator._Set_next(pos, nodes[0]); - return this._Insert_by_range(pos, first, last); - } - - private _Insert_by_range< - InputIterator extends Readonly>, - >( - pos: ForwardList.Iterator, - first: InputIterator, - last: InputIterator, - ): ForwardList.Iterator { - const nodes: ForwardList.Iterator[] = []; - let count: number = 0; - - for (; !first.equals(last); first = first.next()) { - const node = ForwardList.Iterator.create( - this.ptr_, - null!, - first.value, - ); - nodes.push(node); - - ++count; - } - if (count === 0) return pos; - - for (let i: number = 0; i < count - 1; ++i) - ForwardList.Iterator._Set_next(nodes[i], nodes[i + 1]); - ForwardList.Iterator._Set_next(nodes[nodes.length - 1], pos.next()); - ForwardList.Iterator._Set_next(pos, nodes[0]); - - this.size_ += count; - return nodes[nodes.length - 1]; - } + this.size_ += count; + return nodes[nodes.length - 1]; + } - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- ERASE --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public pop_front(): void { - this.erase_after(this.before_begin()); - } - - /** - * Erase an element. - * - * @param it Position to erase after. - * @return Iterator to the erased element. - */ - public erase_after(it: ForwardList.Iterator): ForwardList.Iterator; - - /** - * Erase elements. - * - * @param first Range of the first position to erase after. - * @param last Rangee of the last position to erase. - * @return Iterator to the last removed element. - */ - public erase_after( - first: ForwardList.Iterator, - last: ForwardList.Iterator, - ): ForwardList.Iterator; - - public erase_after( - first: ForwardList.Iterator, - last: ForwardList.Iterator = advance(first, 2), - ): ForwardList.Iterator { - // SHRINK SIZE - this.size_ -= Math.max(0, distance(first, last) - 1); - - // RE-CONNECT - ForwardList.Iterator._Set_next(first, last); - return last; - } - - /* =============================================================== + /** + * @inheritDoc + */ + public pop_front(): void { + this.erase_after(this.before_begin()); + } + + /** + * Erase an element. + * + * @param it Position to erase after. + * @return Iterator to the erased element. + */ + public erase_after(it: ForwardList.Iterator): ForwardList.Iterator; + + /** + * Erase elements. + * + * @param first Range of the first position to erase after. + * @param last Rangee of the last position to erase. + * @return Iterator to the last removed element. + */ + public erase_after( + first: ForwardList.Iterator, + last: ForwardList.Iterator, + ): ForwardList.Iterator; + + public erase_after( + first: ForwardList.Iterator, + last: ForwardList.Iterator = advance(first, 2), + ): ForwardList.Iterator { + // SHRINK SIZE + this.size_ -= Math.max(0, distance(first, last) - 1); + + // RE-CONNECT + ForwardList.Iterator._Set_next(first, last); + return last; + } + + /* =============================================================== ALGORITHMS - UNIQUE & REMOVE(_IF) - MERGE & SPLICE @@ -377,279 +369,266 @@ export class ForwardList ================================================================== UNIQUE & REMOVE(_IF) --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public unique(binary_pred: BinaryPredicator = equal_to): void { - for ( - let it = this.begin().next(); - !it.equals(this.end()); - it = it.next() - ) { - const next_it = it.next(); - if (next_it.equals(this.end())) break; - - if (binary_pred(it.value, next_it.value)) this.erase_after(it); - } + /** + * @inheritDoc + */ + public unique(binary_pred: BinaryPredicator = equal_to): void { + for (let it = this.begin().next(); !it.equals(this.end()); it = it.next()) { + const next_it = it.next(); + if (next_it.equals(this.end())) break; + + if (binary_pred(it.value, next_it.value)) this.erase_after(it); } - - /** - * @inheritDoc - */ - public remove(val: T): void { - return this.remove_if((elem) => equal_to(elem, val)); + } + + /** + * @inheritDoc + */ + public remove(val: T): void { + return this.remove_if((elem) => equal_to(elem, val)); + } + + /** + * @inheritDoc + */ + public remove_if(pred: UnaryPredicator): void { + let count: number = 0; + + for ( + let it = this.before_begin(); + !it.next().equals(this.end()); + it = it.next() + ) + if (pred(it.next().value) === true) { + ForwardList.Iterator._Set_next(it, it.next().next()); + ++count; + } + this.size_ -= count; + } + + /* --------------------------------------------------------------- + MERGE & SPLICE + --------------------------------------------------------------- */ + /** + * @inheritDoc + */ + public merge(from: ForwardList, comp: Comparator = less): void { + if (this === >from) return; + + let it = this.before_begin(); + while (from.empty() === false) { + const value = from.begin().value; + while (!it.next().equals(this.end()) && comp(it.next().value, value)) + it = it.next(); + + this.splice_after(it, from, from.before_begin()); } + } + + /** + * Transfer elements. + * + * @param pos Position to insert after. + * @param from Target container to transfer. + */ + public splice_after(pos: ForwardList.Iterator, from: ForwardList): void; + + /** + * Transfer a single element. + * + * @param pos Position to insert after. + * @param from Target container to transfer. + * @param before Previous position of the single element to transfer. + */ + public splice_after( + pos: ForwardList.Iterator, + from: ForwardList, + before: ForwardList.Iterator, + ): void; + + /** + * Transfer range elements. + * + * @param pos Position to insert after. + * @param from Target container to transfer. + * @param first Range of previous of the first position to transfer. + * @param last Rangee of the last position to transfer. + */ + public splice_after( + pos: ForwardList.Iterator, + from: ForwardList, + first_before: ForwardList.Iterator, + last: ForwardList.Iterator, + ): void; + + public splice_after( + pos: ForwardList.Iterator, + from: ForwardList, + first_before: ForwardList.Iterator = from.before_begin(), + last: ForwardList.Iterator = first_before.next().next(), + ): void { + // DEFAULT PARAMETERS + if (last === null) last = from.end(); + + // INSERT & ERASE + this.insert_after(pos, first_before.next(), last!); + from.erase_after(first_before, last!); + } + + /* --------------------------------------------------------------- + SORT + --------------------------------------------------------------- */ + /** + * @inheritDoc + */ + public sort(comp: Comparator = less): void { + const vec = new Vector(this.begin(), this.end()); + sort_func(vec.begin(), vec.end(), comp); + + this.assign(vec.begin(), vec.end()); + } + + /** + * @inheritDoc + */ + public reverse(): void { + const vec = new Vector(this.begin(), this.end()); + this.assign(vec.rbegin(), vec.rend()); + } + + /* --------------------------------------------------------------- + UTILITIES + --------------------------------------------------------------- */ + /** + * @inheritDoc + */ + public swap(obj: ForwardList): void { + // SIZE AND NODES + [this.size_, obj.size_] = [obj.size_, this.size_]; + [this.before_begin_, obj.before_begin_] = [ + obj.before_begin_, + this.before_begin_, + ]; + [this.end_, obj.end_] = [obj.end_, this.end_]; + + // POINTER OF THE SOURCE + [this.ptr_, obj.ptr_] = [obj.ptr_, this.ptr_]; + [this.ptr_.value, obj.ptr_.value] = [obj.ptr_.value, this.ptr_.value]; + } + + /** + * Native function for `JSON.stringify()`. + * + * @return An array containing children elements. + */ + public toJSON(): Array { + const ret: T[] = []; + for (const elem of this) ret.push(elem); + + return ret; + } +} - /** - * @inheritDoc - */ - public remove_if(pred: UnaryPredicator): void { - let count: number = 0; - - for ( - let it = this.before_begin(); - !it.next().equals(this.end()); - it = it.next() - ) - if (pred(it.next().value) === true) { - ForwardList.Iterator._Set_next(it, it.next().next()); - ++count; - } - this.size_ -= count; - } +/** + * + */ +export namespace ForwardList { + /** + * Iterator of {@link ForwardList} + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class Iterator implements IForwardIterator> { + private source_ptr_: IPointer>; + private next_: Iterator; + private value_: T | undefined; /* --------------------------------------------------------------- - MERGE & SPLICE - --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public merge(from: ForwardList, comp: Comparator = less): void { - if (this === >from) return; - - let it = this.before_begin(); - while (from.empty() === false) { - const value = from.begin().value; - while ( - !it.next().equals(this.end()) && - comp(it.next().value, value) - ) - it = it.next(); - - this.splice_after(it, from, from.before_begin()); - } + CONSTRUCTORS + --------------------------------------------------------------- */ + private constructor( + source: IPointer>, + next: Iterator, + value?: T, + ) { + this.source_ptr_ = source; + this.next_ = next; + + this.value_ = value; } /** - * Transfer elements. - * - * @param pos Position to insert after. - * @param from Target container to transfer. - */ - public splice_after( - pos: ForwardList.Iterator, - from: ForwardList, - ): void; - - /** - * Transfer a single element. - * - * @param pos Position to insert after. - * @param from Target container to transfer. - * @param before Previous position of the single element to transfer. + * @internal */ - public splice_after( - pos: ForwardList.Iterator, - from: ForwardList, - before: ForwardList.Iterator, - ): void; + public static create( + source: IPointer>, + next: Iterator, + value?: T, + ) { + return new Iterator(source, next, value); + } + /* --------------------------------------------------------------- + ACCESSORS + --------------------------------------------------------------- */ /** - * Transfer range elements. + * Get source container. * - * @param pos Position to insert after. - * @param from Target container to transfer. - * @param first Range of previous of the first position to transfer. - * @param last Rangee of the last position to transfer. + * @return The source container. */ - public splice_after( - pos: ForwardList.Iterator, - from: ForwardList, - first_before: ForwardList.Iterator, - last: ForwardList.Iterator, - ): void; - - public splice_after( - pos: ForwardList.Iterator, - from: ForwardList, - first_before: ForwardList.Iterator = from.before_begin(), - last: ForwardList.Iterator = first_before.next().next(), - ): void { - // DEFAULT PARAMETERS - if (last === null) last = from.end(); - - // INSERT & ERASE - this.insert_after(pos, first_before.next(), last!); - from.erase_after(first_before, last!); + public source(): ForwardList { + return this.source_ptr_.value; } - /* --------------------------------------------------------------- - SORT - --------------------------------------------------------------- */ /** * @inheritDoc */ - public sort(comp: Comparator = less): void { - const vec = new Vector(this.begin(), this.end()); - sort_func(vec.begin(), vec.end(), comp); - - this.assign(vec.begin(), vec.end()); + public get value(): T { + this._Try_value(); + return this.value_!; } /** * @inheritDoc */ - public reverse(): void { - const vec = new Vector(this.begin(), this.end()); - this.assign(vec.rbegin(), vec.rend()); + public set value(val: T) { + this._Try_value(); + this.value_ = val; } - /* --------------------------------------------------------------- - UTILITIES - --------------------------------------------------------------- */ + private _Try_value(): void { + if (this.value_ === undefined) { + const source: ForwardList = this.source(); + + if (this.equals(source.end()) === true) + throw ErrorGenerator.iterator_end_value(source); + else if (this.equals(source.before_begin()) === true) + throw ErrorGenerator.iterator_end_value(source, "before_begin"); + } + } + + /* --------------------------------------------------------- + MOVERS + --------------------------------------------------------- */ /** * @inheritDoc */ - public swap(obj: ForwardList): void { - // SIZE AND NODES - [this.size_, obj.size_] = [obj.size_, this.size_]; - [this.before_begin_, obj.before_begin_] = [ - obj.before_begin_, - this.before_begin_, - ]; - [this.end_, obj.end_] = [obj.end_, this.end_]; - - // POINTER OF THE SOURCE - [this.ptr_, obj.ptr_] = [obj.ptr_, this.ptr_]; - [this.ptr_.value, obj.ptr_.value] = [obj.ptr_.value, this.ptr_.value]; + public next(): Iterator { + return this.next_; } /** - * Native function for `JSON.stringify()`. - * - * @return An array containing children elements. + * @inheritDoc */ - public toJSON(): Array { - const ret: T[] = []; - for (const elem of this) ret.push(elem); - - return ret; + public equals(obj: Iterator): boolean { + return this === obj; } -} -/** - * - */ -export namespace ForwardList { /** - * Iterator of {@link ForwardList} - * - * @author Jeongho Nam - https://github.com/samchon + * @internal */ - export class Iterator implements IForwardIterator> { - private source_ptr_: IPointer>; - private next_: Iterator; - private value_: T | undefined; - - /* --------------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------------- */ - private constructor( - source: IPointer>, - next: Iterator, - value?: T, - ) { - this.source_ptr_ = source; - this.next_ = next; - - this.value_ = value; - } - - /** - * @internal - */ - public static create( - source: IPointer>, - next: Iterator, - value?: T, - ) { - return new Iterator(source, next, value); - } - - /* --------------------------------------------------------------- - ACCESSORS - --------------------------------------------------------------- */ - /** - * Get source container. - * - * @return The source container. - */ - public source(): ForwardList { - return this.source_ptr_.value; - } - - /** - * @inheritDoc - */ - public get value(): T { - this._Try_value(); - return this.value_!; - } - - /** - * @inheritDoc - */ - public set value(val: T) { - this._Try_value(); - this.value_ = val; - } - - private _Try_value(): void { - if (this.value_ === undefined) { - const source: ForwardList = this.source(); - - if (this.equals(source.end()) === true) - throw ErrorGenerator.iterator_end_value(source); - else if (this.equals(source.before_begin()) === true) - throw ErrorGenerator.iterator_end_value( - source, - "before_begin", - ); - } - } - - /* --------------------------------------------------------- - MOVERS - --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public next(): Iterator { - return this.next_; - } - - /** - * @inheritDoc - */ - public equals(obj: Iterator): boolean { - return this === obj; - } - - /** - * @internal - */ - public static _Set_next(it: Iterator, next: Iterator): void { - it.next_ = next; - } + public static _Set_next(it: Iterator, next: Iterator): void { + it.next_ = next; } + } } diff --git a/src/container/HashMap.ts b/src/container/HashMap.ts index 2d19151e..74e7cb0d 100644 --- a/src/container/HashMap.ts +++ b/src/container/HashMap.ts @@ -1,375 +1,367 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { UniqueMap } from "../base/container/UniqueMap"; import { IHashMap } from "../base/container/IHashMap"; +import { UniqueMap } from "../base/container/UniqueMap"; import { IHashContainer } from "../internal/container/associative/IHashContainer"; - import { MapElementList } from "../internal/container/associative/MapElementList"; +import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; +import { Hasher } from "../internal/functional/Hasher"; +import { Temporary } from "../internal/functional/Temporary"; import { MapHashBuckets } from "../internal/hash/MapHashBuckets"; - import { IForwardIterator } from "../iterator/IForwardIterator"; -import { IPair } from "../utility/IPair"; import { Entry } from "../utility/Entry"; +import { IPair } from "../utility/IPair"; import { Pair } from "../utility/Pair"; -import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; -import { Hasher } from "../internal/functional/Hasher"; -import { Temporary } from "../internal/functional/Temporary"; - /** * Unique-key Map based on Hash buckets. * * @author Jeongho Nam - https://github.com/samchon */ export class HashMap - extends UniqueMap< - Key, - T, - HashMap, - HashMap.Iterator, - HashMap.ReverseIterator - > - implements IHashMap> + extends UniqueMap< + Key, + T, + HashMap, + HashMap.Iterator, + HashMap.ReverseIterator + > + implements IHashMap> { - private buckets_!: MapHashBuckets>; + private buckets_!: MapHashBuckets>; - /* ========================================================= + /* ========================================================= CONSTRUCTORS & SEMI-CONSTRUCTORS - CONSTRUCTORS - ASSIGN & CLEAR ============================================================ CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor(hash?: Hasher, equal?: BinaryPredicator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor( - items: IPair[], - hash?: Hasher, - equal?: BinaryPredicator, + /** + * Default Constructor. + * + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor(hash?: Hasher, equal?: BinaryPredicator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor( + items: IPair[], + hash?: Hasher, + equal?: BinaryPredicator, + ); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: HashMap); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor( + first: Readonly>>, + last: Readonly>>, + hash?: Hasher, + equal?: BinaryPredicator, + ); + + public constructor(...args: any[]) { + super((thisArg) => new MapElementList(thisArg)); + + IHashContainer.construct< + Key, + Entry, + HashMap, + HashMap.Iterator, + HashMap.ReverseIterator, + IPair + >( + this, + HashMap, + (hash, pred) => { + this.buckets_ = new MapHashBuckets(this as HashMap, hash, pred); + }, + ...args, ); + } - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: HashMap); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor( - first: Readonly>>, - last: Readonly>>, - hash?: Hasher, - equal?: BinaryPredicator, - ); - - public constructor(...args: any[]) { - super((thisArg) => new MapElementList(thisArg)); - - IHashContainer.construct< - Key, - Entry, - HashMap, - HashMap.Iterator, - HashMap.ReverseIterator, - IPair - >( - this, - HashMap, - (hash, pred) => { - this.buckets_ = new MapHashBuckets( - this as HashMap, - hash, - pred, - ); - }, - ...args, - ); - } - - /* --------------------------------------------------------- + /* --------------------------------------------------------- ASSIGN & CLEAR --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public clear(): void { - this.buckets_.clear(); + /** + * @inheritDoc + */ + public clear(): void { + this.buckets_.clear(); + + super.clear(); + } + + /** + * @inheritDoc + */ + public swap(obj: HashMap): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + MapElementList._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, + ); - super.clear(); - } + // SWAP BUCKETS + MapHashBuckets._Swap_source(this.buckets_, obj.buckets_); + [this.buckets_, obj.buckets_] = [obj.buckets_, this.buckets_]; + } - /** - * @inheritDoc - */ - public swap(obj: HashMap): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - MapElementList._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP BUCKETS - MapHashBuckets._Swap_source(this.buckets_, obj.buckets_); - [this.buckets_, obj.buckets_] = [obj.buckets_, this.buckets_]; - } - - /* ========================================================= + /* ========================================================= ACCESSORS - MEMBER - HASH ============================================================ MEMBER --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public find(key: Key): HashMap.Iterator { - return this.buckets_.find(key); - } - - /** - * @inheritDoc - */ - public begin(): HashMap.Iterator; - /** - * @inheritDoc - */ - public begin(index: number): HashMap.Iterator; - public begin(index: number | null = null): HashMap.Iterator { - if (index === null) return super.begin(); - else return this.buckets_.at(index)[0]; - } - - /** - * @inheritDoc - */ - public end(): HashMap.Iterator; - /** - * @inheritDoc - */ - public end(index: number): HashMap.Iterator; - public end(index: number | null = null): HashMap.Iterator { - if (index === null) return super.end(); - else { - const bucket = this.buckets_.at(index); - return bucket[bucket.length - 1].next(); - } - } - - /** - * @inheritDoc - */ - public rbegin(): HashMap.ReverseIterator; - /** - * @inheritDoc - */ - public rbegin(index: number): HashMap.ReverseIterator; - public rbegin( - index: number | null = null, - ): HashMap.ReverseIterator { - return this.end(index!).reverse(); - } - - /** - * @inheritDoc - */ - public rend(): HashMap.ReverseIterator; - /** - * @inheritDoc - */ - public rend(index: number): HashMap.ReverseIterator; - public rend(index: number | null = null): HashMap.ReverseIterator { - return this.begin(index!).reverse(); + /** + * @inheritDoc + */ + public find(key: Key): HashMap.Iterator { + return this.buckets_.find(key); + } + + /** + * @inheritDoc + */ + public begin(): HashMap.Iterator; + /** + * @inheritDoc + */ + public begin(index: number): HashMap.Iterator; + public begin(index: number | null = null): HashMap.Iterator { + if (index === null) return super.begin(); + else return this.buckets_.at(index)[0]; + } + + /** + * @inheritDoc + */ + public end(): HashMap.Iterator; + /** + * @inheritDoc + */ + public end(index: number): HashMap.Iterator; + public end(index: number | null = null): HashMap.Iterator { + if (index === null) return super.end(); + else { + const bucket = this.buckets_.at(index); + return bucket[bucket.length - 1].next(); } - - /* --------------------------------------------------------- + } + + /** + * @inheritDoc + */ + public rbegin(): HashMap.ReverseIterator; + /** + * @inheritDoc + */ + public rbegin(index: number): HashMap.ReverseIterator; + public rbegin(index: number | null = null): HashMap.ReverseIterator { + return this.end(index!).reverse(); + } + + /** + * @inheritDoc + */ + public rend(): HashMap.ReverseIterator; + /** + * @inheritDoc + */ + public rend(index: number): HashMap.ReverseIterator; + public rend(index: number | null = null): HashMap.ReverseIterator { + return this.begin(index!).reverse(); + } + + /* --------------------------------------------------------- HASH --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public bucket_count(): number { - return this.buckets_.length(); - } - - /** - * @inheritDoc - */ - public bucket_size(index: number): number { - return this.buckets_.at(index).length; - } - - /** - * @inheritDoc - */ - public load_factor(): number { - return this.buckets_.load_factor(); - } - - /** - * @inheritDoc - */ - public hash_function(): Hasher { - return this.buckets_.hash_function(); - } - - /** - * @inheritDoc - */ - public key_eq(): BinaryPredicator { - return this.buckets_.key_eq(); - } - - /** - * @inheritDoc - */ - public bucket(key: Key): number { - return this.hash_function()(key) % this.buckets_.length(); - } - - /** - * @inheritDoc - */ - public max_load_factor(): number; - /** - * @inheritDoc - */ - public max_load_factor(z: number): void; - public max_load_factor(z: number | null = null): any { - return this.buckets_.max_load_factor(z!); - } - - /** - * @inheritDoc - */ - public reserve(n: number): void { - this.buckets_.reserve(n); - } - - /** - * @inheritDoc - */ - public rehash(n: number): void { - this.buckets_.rehash(n); - } - - /* ========================================================= + /** + * @inheritDoc + */ + public bucket_count(): number { + return this.buckets_.length(); + } + + /** + * @inheritDoc + */ + public bucket_size(index: number): number { + return this.buckets_.at(index).length; + } + + /** + * @inheritDoc + */ + public load_factor(): number { + return this.buckets_.load_factor(); + } + + /** + * @inheritDoc + */ + public hash_function(): Hasher { + return this.buckets_.hash_function(); + } + + /** + * @inheritDoc + */ + public key_eq(): BinaryPredicator { + return this.buckets_.key_eq(); + } + + /** + * @inheritDoc + */ + public bucket(key: Key): number { + return this.hash_function()(key) % this.buckets_.length(); + } + + /** + * @inheritDoc + */ + public max_load_factor(): number; + /** + * @inheritDoc + */ + public max_load_factor(z: number): void; + public max_load_factor(z: number | null = null): any { + return this.buckets_.max_load_factor(z!); + } + + /** + * @inheritDoc + */ + public reserve(n: number): void { + this.buckets_.reserve(n); + } + + /** + * @inheritDoc + */ + public rehash(n: number): void { + this.buckets_.rehash(n); + } + + /* ========================================================= ELEMENTS I/O - INSERT - POST-PROCESS ============================================================ INSERT --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public emplace(key: Key, val: T): Pair, boolean> { - // TEST WHETHER EXIST - let it: HashMap.Iterator = this.find(key); - if (it.equals(this.end()) === false) return new Pair(it, false); - - // INSERT - this.data_.push(new Entry(key, val)); - it = it.prev(); - - // POST-PROCESS - this._Handle_insert(it, it.next()); - - return new Pair(it, true); - } - - /** - * @inheritDoc - */ - public emplace_hint( - hint: HashMap.Iterator, - key: Key, - val: T, - ): HashMap.Iterator { - // FIND DUPLICATED KEY - let it: HashMap.Iterator = this.find(key); - if (it.equals(this.end()) === true) { - // INSERT - it = this.data_.insert(hint, new Entry(key, val)); - - // POST-PROCESS - this._Handle_insert(it, it.next()); - } - return it; + /** + * @inheritDoc + */ + public emplace(key: Key, val: T): Pair, boolean> { + // TEST WHETHER EXIST + let it: HashMap.Iterator = this.find(key); + if (it.equals(this.end()) === false) return new Pair(it, false); + + // INSERT + this.data_.push(new Entry(key, val)); + it = it.prev(); + + // POST-PROCESS + this._Handle_insert(it, it.next()); + + return new Pair(it, true); + } + + /** + * @inheritDoc + */ + public emplace_hint( + hint: HashMap.Iterator, + key: Key, + val: T, + ): HashMap.Iterator { + // FIND DUPLICATED KEY + let it: HashMap.Iterator = this.find(key); + if (it.equals(this.end()) === true) { + // INSERT + it = this.data_.insert(hint, new Entry(key, val)); + + // POST-PROCESS + this._Handle_insert(it, it.next()); } + return it; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert( - first: HashMap.Iterator, - last: HashMap.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.buckets_.insert(first); - } - - protected _Handle_erase( - first: HashMap.Iterator, - last: HashMap.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.buckets_.erase(first); - } + protected _Handle_insert( + first: HashMap.Iterator, + last: HashMap.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) + this.buckets_.insert(first); + } + + protected _Handle_erase( + first: HashMap.Iterator, + last: HashMap.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) + this.buckets_.erase(first); + } } /** * */ export namespace HashMap { - // HEAD - /** - * Iterator of {@link HashMap} - */ - export type Iterator = MapElementList.Iterator< - Key, - T, - true, - HashMap - >; - - /** - * Reverse iterator of {@link HashMap} - */ - export type ReverseIterator = MapElementList.ReverseIterator< - Key, - T, - true, - HashMap - >; - - // BODY - export const Iterator = MapElementList.Iterator; - export const ReverseIterator = MapElementList.ReverseIterator; + // HEAD + /** + * Iterator of {@link HashMap} + */ + export type Iterator = MapElementList.Iterator< + Key, + T, + true, + HashMap + >; + + /** + * Reverse iterator of {@link HashMap} + */ + export type ReverseIterator = MapElementList.ReverseIterator< + Key, + T, + true, + HashMap + >; + + // BODY + export const Iterator = MapElementList.Iterator; + export const ReverseIterator = MapElementList.ReverseIterator; } diff --git a/src/container/HashMultiMap.ts b/src/container/HashMultiMap.ts index af090885..f58853e3 100644 --- a/src/container/HashMultiMap.ts +++ b/src/container/HashMultiMap.ts @@ -1,24 +1,22 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { MultiMap } from "../base/container/MultiMap"; import { IHashMap } from "../base/container/IHashMap"; +import { MultiMap } from "../base/container/MultiMap"; import { IHashContainer } from "../internal/container/associative/IHashContainer"; - import { MapElementList } from "../internal/container/associative/MapElementList"; +import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; +import { Hasher } from "../internal/functional/Hasher"; +import { Temporary } from "../internal/functional/Temporary"; import { MapHashBuckets } from "../internal/hash/MapHashBuckets"; - import { NativeArrayIterator } from "../internal/iterator/disposable/NativeArrayIterator"; import { IForwardIterator } from "../iterator/IForwardIterator"; -import { IPair } from "../utility/IPair"; import { Entry } from "../utility/Entry"; - -import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; -import { Hasher } from "../internal/functional/Hasher"; -import { Temporary } from "../internal/functional/Temporary"; +import { IPair } from "../utility/IPair"; /** * Multiple-key Map based on Hash buckets. @@ -26,397 +24,397 @@ import { Temporary } from "../internal/functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export class HashMultiMap - extends MultiMap< - Key, - T, - HashMultiMap, - HashMultiMap.Iterator, - HashMultiMap.ReverseIterator - > - implements IHashMap> + extends MultiMap< + Key, + T, + HashMultiMap, + HashMultiMap.Iterator, + HashMultiMap.ReverseIterator + > + implements IHashMap> { - private buckets_!: MapHashBuckets>; + private buckets_!: MapHashBuckets>; - /* ========================================================= + /* ========================================================= CONSTRUCTORS & SEMI-CONSTRUCTORS - CONSTRUCTORS - ASSIGN & CLEAR ============================================================ CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor(hash?: Hasher, equal?: BinaryPredicator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor( - items: IPair[], - hash?: Hasher, - equal?: BinaryPredicator, - ); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: HashMultiMap); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor( - first: Readonly>>, - last: Readonly>>, - hash?: Hasher, - equal?: BinaryPredicator, - ); - - public constructor(...args: any[]) { - super((thisArg) => new MapElementList(thisArg)); - - IHashContainer.construct< - Key, - Entry, - HashMultiMap, - HashMultiMap.Iterator, - HashMultiMap.ReverseIterator, - IPair - >( - this, - HashMultiMap, - (hash, pred) => { - this.buckets_ = new MapHashBuckets( - this as HashMultiMap, - hash, - pred, - ); - }, - ...args, + /** + * Default Constructor. + * + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor(hash?: Hasher, equal?: BinaryPredicator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor( + items: IPair[], + hash?: Hasher, + equal?: BinaryPredicator, + ); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: HashMultiMap); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor( + first: Readonly>>, + last: Readonly>>, + hash?: Hasher, + equal?: BinaryPredicator, + ); + + public constructor(...args: any[]) { + super((thisArg) => new MapElementList(thisArg)); + + IHashContainer.construct< + Key, + Entry, + HashMultiMap, + HashMultiMap.Iterator, + HashMultiMap.ReverseIterator, + IPair + >( + this, + HashMultiMap, + (hash, pred) => { + this.buckets_ = new MapHashBuckets( + this as HashMultiMap, + hash, + pred, ); - } + }, + ...args, + ); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ASSIGN & CLEAR --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public clear(): void { - this.buckets_.clear(); - - super.clear(); - } - - /** - * @inheritDoc - */ - public swap(obj: HashMultiMap): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - MapElementList._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); + /** + * @inheritDoc + */ + public clear(): void { + this.buckets_.clear(); + + super.clear(); + } + + /** + * @inheritDoc + */ + public swap(obj: HashMultiMap): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + MapElementList._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, + ); - // SWAP BUCKETS - MapHashBuckets._Swap_source(this.buckets_, obj.buckets_); - [this.buckets_, obj.buckets_] = [obj.buckets_, this.buckets_]; - } + // SWAP BUCKETS + MapHashBuckets._Swap_source(this.buckets_, obj.buckets_); + [this.buckets_, obj.buckets_] = [obj.buckets_, this.buckets_]; + } - /* ========================================================= + /* ========================================================= ACCESSORS - MEMBER - HASH ============================================================ MEMBER --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public find(key: Key): HashMultiMap.Iterator { - return this.buckets_.find(key); - } - - /** - * @inheritDoc - */ - public count(key: Key): number { - // FIND MATCHED BUCKET - const index = this.bucket(key); - const bucket = this.buckets_.at(index); - - // ITERATE THE BUCKET - let cnt: number = 0; - for (let it of bucket) if (this.buckets_.key_eq()(it.first, key)) ++cnt; - - return cnt; - } - - /** - * @inheritDoc - */ - public begin(): HashMultiMap.Iterator; - /** - * @inheritDoc - */ - public begin(index: number): HashMultiMap.Iterator; - public begin(index: number | null = null): HashMultiMap.Iterator { - if (index === null) return super.begin(); - else return this.buckets_.at(index)[0]; - } - - /** - * @inheritDoc - */ - public end(): HashMultiMap.Iterator; - /** - * @inheritDoc - */ - public end(index: number): HashMultiMap.Iterator; - public end(index: number | null = null): HashMultiMap.Iterator { - if (index === null) return super.end(); - else { - const bucket = this.buckets_.at(index); - return bucket[bucket.length - 1].next(); - } - } - - /** - * @inheritDoc - */ - public rbegin(): HashMultiMap.ReverseIterator; - /** - * @inheritDoc - */ - public rbegin(index: number): HashMultiMap.ReverseIterator; - public rbegin( - index: number | null = null, - ): HashMultiMap.ReverseIterator { - return this.end(index!).reverse(); - } - - /** - * @inheritDoc - */ - public rend(): HashMultiMap.ReverseIterator; - /** - * @inheritDoc - */ - public rend(index: number): HashMultiMap.ReverseIterator; - public rend( - index: number | null = null, - ): HashMultiMap.ReverseIterator { - return this.begin(index!).reverse(); + /** + * @inheritDoc + */ + public find(key: Key): HashMultiMap.Iterator { + return this.buckets_.find(key); + } + + /** + * @inheritDoc + */ + public count(key: Key): number { + // FIND MATCHED BUCKET + const index = this.bucket(key); + const bucket = this.buckets_.at(index); + + // ITERATE THE BUCKET + let cnt: number = 0; + for (let it of bucket) if (this.buckets_.key_eq()(it.first, key)) ++cnt; + + return cnt; + } + + /** + * @inheritDoc + */ + public begin(): HashMultiMap.Iterator; + /** + * @inheritDoc + */ + public begin(index: number): HashMultiMap.Iterator; + public begin(index: number | null = null): HashMultiMap.Iterator { + if (index === null) return super.begin(); + else return this.buckets_.at(index)[0]; + } + + /** + * @inheritDoc + */ + public end(): HashMultiMap.Iterator; + /** + * @inheritDoc + */ + public end(index: number): HashMultiMap.Iterator; + public end(index: number | null = null): HashMultiMap.Iterator { + if (index === null) return super.end(); + else { + const bucket = this.buckets_.at(index); + return bucket[bucket.length - 1].next(); } - - /* --------------------------------------------------------- + } + + /** + * @inheritDoc + */ + public rbegin(): HashMultiMap.ReverseIterator; + /** + * @inheritDoc + */ + public rbegin(index: number): HashMultiMap.ReverseIterator; + public rbegin( + index: number | null = null, + ): HashMultiMap.ReverseIterator { + return this.end(index!).reverse(); + } + + /** + * @inheritDoc + */ + public rend(): HashMultiMap.ReverseIterator; + /** + * @inheritDoc + */ + public rend(index: number): HashMultiMap.ReverseIterator; + public rend( + index: number | null = null, + ): HashMultiMap.ReverseIterator { + return this.begin(index!).reverse(); + } + + /* --------------------------------------------------------- HASH --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public bucket_count(): number { - return this.buckets_.length(); - } - - /** - * @inheritDoc - */ - public bucket_size(index: number): number { - return this.buckets_.at(index).length; - } - - /** - * @inheritDoc - */ - public load_factor(): number { - return this.buckets_.load_factor(); - } - - /** - * @inheritDoc - */ - public hash_function(): Hasher { - return this.buckets_.hash_function(); - } - - /** - * @inheritDoc - */ - public key_eq(): BinaryPredicator { - return this.buckets_.key_eq(); - } - - /** - * @inheritDoc - */ - public bucket(key: Key): number { - return this.hash_function()(key) % this.buckets_.length(); - } - - /** - * @inheritDoc - */ - public max_load_factor(): number; - /** - * @inheritDoc - */ - public max_load_factor(z: number): void; - public max_load_factor(z: number | null = null): any { - return this.buckets_.max_load_factor(z!); - } - - /** - * @inheritDoc - */ - public reserve(n: number): void { - this.buckets_.reserve(n); - } - - /** - * @inheritDoc - */ - public rehash(n: number): void { - if (n <= this.bucket_count()) return; - - this.buckets_.rehash(n); - } - - protected _Key_eq(x: Key, y: Key): boolean { - return this.key_eq()(x, y); - } - - /* ========================================================= + /** + * @inheritDoc + */ + public bucket_count(): number { + return this.buckets_.length(); + } + + /** + * @inheritDoc + */ + public bucket_size(index: number): number { + return this.buckets_.at(index).length; + } + + /** + * @inheritDoc + */ + public load_factor(): number { + return this.buckets_.load_factor(); + } + + /** + * @inheritDoc + */ + public hash_function(): Hasher { + return this.buckets_.hash_function(); + } + + /** + * @inheritDoc + */ + public key_eq(): BinaryPredicator { + return this.buckets_.key_eq(); + } + + /** + * @inheritDoc + */ + public bucket(key: Key): number { + return this.hash_function()(key) % this.buckets_.length(); + } + + /** + * @inheritDoc + */ + public max_load_factor(): number; + /** + * @inheritDoc + */ + public max_load_factor(z: number): void; + public max_load_factor(z: number | null = null): any { + return this.buckets_.max_load_factor(z!); + } + + /** + * @inheritDoc + */ + public reserve(n: number): void { + this.buckets_.reserve(n); + } + + /** + * @inheritDoc + */ + public rehash(n: number): void { + if (n <= this.bucket_count()) return; + + this.buckets_.rehash(n); + } + + protected _Key_eq(x: Key, y: Key): boolean { + return this.key_eq()(x, y); + } + + /* ========================================================= ELEMENTS I/O - INSERT - POST-PROCESS ============================================================ INSERT --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public emplace(key: Key, val: T): HashMultiMap.Iterator { - // INSERT - const it = this.data_.insert(this.data_.end(), new Entry(key, val)); - - this._Handle_insert(it, it.next()); // POST-PROCESS - return it; - } - - /** - * @inheritDoc - */ - public emplace_hint( - hint: HashMultiMap.Iterator, - key: Key, - val: T, - ): HashMultiMap.Iterator { - // INSERT - const it = this.data_.insert(hint, new Entry(key, val)); - - // POST-PROCESS - this._Handle_insert(it, it.next()); - - return it; - } - - protected _Insert_by_range< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - >(first: InputIterator, last: InputIterator): void { - //-------- - // INSERTIONS - //-------- - // PRELIMINARIES - const entries: Array> = []; - for (let it = first; !it.equals(last); it = it.next()) - entries.push(new Entry(it.value.first, it.value.second)); - - // INSERT ELEMENTS - const my_first = this.data_.insert( - this.data_.end(), - new NativeArrayIterator(entries, 0), - new NativeArrayIterator(entries, entries.length), - ); + /** + * @inheritDoc + */ + public emplace(key: Key, val: T): HashMultiMap.Iterator { + // INSERT + const it = this.data_.insert(this.data_.end(), new Entry(key, val)); + + this._Handle_insert(it, it.next()); // POST-PROCESS + return it; + } + + /** + * @inheritDoc + */ + public emplace_hint( + hint: HashMultiMap.Iterator, + key: Key, + val: T, + ): HashMultiMap.Iterator { + // INSERT + const it = this.data_.insert(hint, new Entry(key, val)); + + // POST-PROCESS + this._Handle_insert(it, it.next()); + + return it; + } + + protected _Insert_by_range< + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + >(first: InputIterator, last: InputIterator): void { + //-------- + // INSERTIONS + //-------- + // PRELIMINARIES + const entries: Array> = []; + for (let it = first; !it.equals(last); it = it.next()) + entries.push(new Entry(it.value.first, it.value.second)); + + // INSERT ELEMENTS + const my_first = this.data_.insert( + this.data_.end(), + new NativeArrayIterator(entries, 0), + new NativeArrayIterator(entries, entries.length), + ); - //-------- - // HASHING INSERTED ITEMS - //-------- - // IF NEEDED, HASH_BUCKET TO HAVE SUITABLE SIZE - if (this.size() > this.buckets_.capacity()) - this.reserve(Math.max(this.size(), this.buckets_.capacity() * 2)); + //-------- + // HASHING INSERTED ITEMS + //-------- + // IF NEEDED, HASH_BUCKET TO HAVE SUITABLE SIZE + if (this.size() > this.buckets_.capacity()) + this.reserve(Math.max(this.size(), this.buckets_.capacity() * 2)); - // POST-PROCESS - this._Handle_insert(my_first, this.end()); - } + // POST-PROCESS + this._Handle_insert(my_first, this.end()); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert( - first: HashMultiMap.Iterator, - last: HashMultiMap.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.buckets_.insert(first); - } - - protected _Handle_erase( - first: HashMultiMap.Iterator, - last: HashMultiMap.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.buckets_.erase(first); - } + protected _Handle_insert( + first: HashMultiMap.Iterator, + last: HashMultiMap.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) + this.buckets_.insert(first); + } + + protected _Handle_erase( + first: HashMultiMap.Iterator, + last: HashMultiMap.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) + this.buckets_.erase(first); + } } /** * */ export namespace HashMultiMap { - //---- - // PASCAL NOTATION - //---- - // HEAD - /** - * Iterator of {@link HashMultiMap} - */ - export type Iterator = MapElementList.Iterator< - Key, - T, - false, - HashMultiMap - >; - - /** - * Reverse iterator of {@link HashMultiMap} - */ - export type ReverseIterator = MapElementList.ReverseIterator< - Key, - T, - false, - HashMultiMap - >; - - // BODY - export const Iterator = MapElementList.Iterator; - export const ReverseIterator = MapElementList.ReverseIterator; + //---- + // PASCAL NOTATION + //---- + // HEAD + /** + * Iterator of {@link HashMultiMap} + */ + export type Iterator = MapElementList.Iterator< + Key, + T, + false, + HashMultiMap + >; + + /** + * Reverse iterator of {@link HashMultiMap} + */ + export type ReverseIterator = MapElementList.ReverseIterator< + Key, + T, + false, + HashMultiMap + >; + + // BODY + export const Iterator = MapElementList.Iterator; + export const ReverseIterator = MapElementList.ReverseIterator; } diff --git a/src/container/HashMultiSet.ts b/src/container/HashMultiSet.ts index 22c50986..22639c2f 100644 --- a/src/container/HashMultiSet.ts +++ b/src/container/HashMultiSet.ts @@ -1,20 +1,19 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { MultiSet } from "../base/container/MultiSet"; import { IHashSet } from "../base/container/IHashSet"; +import { MultiSet } from "../base/container/MultiSet"; import { IHashContainer } from "../internal/container/associative/IHashContainer"; - import { SetElementList } from "../internal/container/associative/SetElementList"; -import { SetHashBuckets } from "../internal/hash/SetHashBuckets"; - -import { IForwardIterator } from "../iterator/IForwardIterator"; import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; import { Hasher } from "../internal/functional/Hasher"; import { Temporary } from "../internal/functional/Temporary"; +import { SetHashBuckets } from "../internal/hash/SetHashBuckets"; +import { IForwardIterator } from "../iterator/IForwardIterator"; /** * Multiple-key Set based on Hash buckets. @@ -22,363 +21,361 @@ import { Temporary } from "../internal/functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export class HashMultiSet - extends MultiSet< - Key, - HashMultiSet, - HashMultiSet.Iterator, - HashMultiSet.ReverseIterator - > - implements IHashSet> + extends MultiSet< + Key, + HashMultiSet, + HashMultiSet.Iterator, + HashMultiSet.ReverseIterator + > + implements IHashSet> { - private buckets_!: SetHashBuckets>; + private buckets_!: SetHashBuckets>; - /* ========================================================= + /* ========================================================= CONSTRUCTORS & SEMI-CONSTRUCTORS - CONSTRUCTORS - ASSIGN & CLEAR ============================================================ CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor(hash?: Hasher, equal?: BinaryPredicator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor( - items: Key[], - hash?: Hasher, - equal?: BinaryPredicator, + /** + * Default Constructor. + * + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor(hash?: Hasher, equal?: BinaryPredicator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor( + items: Key[], + hash?: Hasher, + equal?: BinaryPredicator, + ); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: HashMultiSet); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor( + first: Readonly>, + last: Readonly>, + hash?: Hasher, + equal?: BinaryPredicator, + ); + + public constructor(...args: any[]) { + super((thisArg) => new SetElementList(thisArg)); + + IHashContainer.construct< + Key, + Key, + HashMultiSet, + HashMultiSet.Iterator, + HashMultiSet.ReverseIterator, + Key + >( + this, + HashMultiSet, + (hash, pred) => { + this.buckets_ = new SetHashBuckets(this, hash, pred); + }, + ...args, ); + } - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: HashMultiSet); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor( - first: Readonly>, - last: Readonly>, - hash?: Hasher, - equal?: BinaryPredicator, - ); - - public constructor(...args: any[]) { - super((thisArg) => new SetElementList(thisArg)); - - IHashContainer.construct< - Key, - Key, - HashMultiSet, - HashMultiSet.Iterator, - HashMultiSet.ReverseIterator, - Key - >( - this, - HashMultiSet, - (hash, pred) => { - this.buckets_ = new SetHashBuckets(this, hash, pred); - }, - ...args, - ); - } - - /* --------------------------------------------------------- + /* --------------------------------------------------------- ASSIGN & CLEAR --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public clear(): void { - this.buckets_.clear(); - - super.clear(); - } + /** + * @inheritDoc + */ + public clear(): void { + this.buckets_.clear(); + + super.clear(); + } + + /** + * @inheritDoc + */ + public swap(obj: HashMultiSet): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + SetElementList._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, + ); - /** - * @inheritDoc - */ - public swap(obj: HashMultiSet): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - SetElementList._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP BUCKETS - SetHashBuckets._Swap_source(this.buckets_, obj.buckets_); - [this.buckets_, obj.buckets_] = [obj.buckets_, this.buckets_]; - } + // SWAP BUCKETS + SetHashBuckets._Swap_source(this.buckets_, obj.buckets_); + [this.buckets_, obj.buckets_] = [obj.buckets_, this.buckets_]; + } - /* ========================================================= + /* ========================================================= ACCESSORS - MEMBER - HASH ============================================================ MEMBER --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public find(key: Key): HashMultiSet.Iterator { - return this.buckets_.find(key); + /** + * @inheritDoc + */ + public find(key: Key): HashMultiSet.Iterator { + return this.buckets_.find(key); + } + + /** + * @inheritDoc + */ + public count(key: Key): number { + // FIND MATCHED BUCKET + const index = this.bucket(key); + const bucket = this.buckets_.at(index); + + // ITERATE THE BUCKET + let cnt: number = 0; + for (let it of bucket) if (this.buckets_.key_eq()(it.value, key)) ++cnt; + + return cnt; + } + + /** + * @inheritDoc + */ + public begin(): HashMultiSet.Iterator; + /** + * @inheritDoc + */ + public begin(index: number): HashMultiSet.Iterator; + public begin(index: number | null = null): HashMultiSet.Iterator { + if (index === null) return super.begin(); + else return this.buckets_.at(index)[0]; + } + + /** + * @inheritDoc + */ + public end(): HashMultiSet.Iterator; + /** + * @inheritDoc + */ + public end(index: number): HashMultiSet.Iterator; + public end(index: number | null = null): HashMultiSet.Iterator { + if (index === null) return super.end(); + else { + const bucket = this.buckets_.at(index); + return bucket[bucket.length - 1].next(); } - - /** - * @inheritDoc - */ - public count(key: Key): number { - // FIND MATCHED BUCKET - const index = this.bucket(key); - const bucket = this.buckets_.at(index); - - // ITERATE THE BUCKET - let cnt: number = 0; - for (let it of bucket) if (this.buckets_.key_eq()(it.value, key)) ++cnt; - - return cnt; - } - - /** - * @inheritDoc - */ - public begin(): HashMultiSet.Iterator; - /** - * @inheritDoc - */ - public begin(index: number): HashMultiSet.Iterator; - public begin(index: number | null = null): HashMultiSet.Iterator { - if (index === null) return super.begin(); - else return this.buckets_.at(index)[0]; - } - - /** - * @inheritDoc - */ - public end(): HashMultiSet.Iterator; - /** - * @inheritDoc - */ - public end(index: number): HashMultiSet.Iterator; - public end(index: number | null = null): HashMultiSet.Iterator { - if (index === null) return super.end(); - else { - const bucket = this.buckets_.at(index); - return bucket[bucket.length - 1].next(); - } - } - - /** - * @inheritDoc - */ - public rbegin(): HashMultiSet.ReverseIterator; - /** - * @inheritDoc - */ - public rbegin(index: number): HashMultiSet.ReverseIterator; - public rbegin( - index: number | null = null, - ): HashMultiSet.ReverseIterator { - return this.end(index!).reverse(); - } - - /** - * @inheritDoc - */ - public rend(): HashMultiSet.ReverseIterator; - /** - * @inheritDoc - */ - public rend(index: number): HashMultiSet.ReverseIterator; - public rend( - index: number | null = null, - ): HashMultiSet.ReverseIterator { - return this.begin(index!).reverse(); - } - - /* --------------------------------------------------------- + } + + /** + * @inheritDoc + */ + public rbegin(): HashMultiSet.ReverseIterator; + /** + * @inheritDoc + */ + public rbegin(index: number): HashMultiSet.ReverseIterator; + public rbegin( + index: number | null = null, + ): HashMultiSet.ReverseIterator { + return this.end(index!).reverse(); + } + + /** + * @inheritDoc + */ + public rend(): HashMultiSet.ReverseIterator; + /** + * @inheritDoc + */ + public rend(index: number): HashMultiSet.ReverseIterator; + public rend(index: number | null = null): HashMultiSet.ReverseIterator { + return this.begin(index!).reverse(); + } + + /* --------------------------------------------------------- HASH --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public bucket_count(): number { - return this.buckets_.length(); - } - - /** - * @inheritDoc - */ - public bucket_size(n: number): number { - return this.buckets_.at(n).length; - } - - /** - * @inheritDoc - */ - public load_factor(): number { - return this.buckets_.load_factor(); - } - - /** - * @inheritDoc - */ - public hash_function(): Hasher { - return this.buckets_.hash_function(); - } - - /** - * @inheritDoc - */ - public key_eq(): BinaryPredicator { - return this.buckets_.key_eq(); - } - - /** - * @inheritDoc - */ - public bucket(key: Key): number { - return this.hash_function()(key) % this.buckets_.length(); - } - - /** - * @inheritDoc - */ - public max_load_factor(): number; - /** - * @inheritDoc - */ - public max_load_factor(z: number): void; - public max_load_factor(z: number | null = null): any { - return this.buckets_.max_load_factor(z!); - } - - /** - * @inheritDoc - */ - public reserve(n: number): void { - this.buckets_.rehash(Math.ceil(n * this.max_load_factor())); - } - - /** - * @inheritDoc - */ - public rehash(n: number): void { - if (n <= this.bucket_count()) return; - - this.buckets_.rehash(n); - } - - protected _Key_eq(x: Key, y: Key): boolean { - return this.key_eq()(x, y); - } - - /* ========================================================= + /** + * @inheritDoc + */ + public bucket_count(): number { + return this.buckets_.length(); + } + + /** + * @inheritDoc + */ + public bucket_size(n: number): number { + return this.buckets_.at(n).length; + } + + /** + * @inheritDoc + */ + public load_factor(): number { + return this.buckets_.load_factor(); + } + + /** + * @inheritDoc + */ + public hash_function(): Hasher { + return this.buckets_.hash_function(); + } + + /** + * @inheritDoc + */ + public key_eq(): BinaryPredicator { + return this.buckets_.key_eq(); + } + + /** + * @inheritDoc + */ + public bucket(key: Key): number { + return this.hash_function()(key) % this.buckets_.length(); + } + + /** + * @inheritDoc + */ + public max_load_factor(): number; + /** + * @inheritDoc + */ + public max_load_factor(z: number): void; + public max_load_factor(z: number | null = null): any { + return this.buckets_.max_load_factor(z!); + } + + /** + * @inheritDoc + */ + public reserve(n: number): void { + this.buckets_.rehash(Math.ceil(n * this.max_load_factor())); + } + + /** + * @inheritDoc + */ + public rehash(n: number): void { + if (n <= this.bucket_count()) return; + + this.buckets_.rehash(n); + } + + protected _Key_eq(x: Key, y: Key): boolean { + return this.key_eq()(x, y); + } + + /* ========================================================= ELEMENTS I/O - INSERT - POST-PROCESS ============================================================ INSERT --------------------------------------------------------- */ - protected _Insert_by_key(key: Key): HashMultiSet.Iterator { - // INSERT - const it = this.data_.insert(this.data_.end(), key); - - this._Handle_insert(it, it.next()); // POST-PROCESS - return it; - } - - protected _Insert_by_hint( - hint: HashMultiSet.Iterator, - key: Key, - ): HashMultiSet.Iterator { - // INSERT - const it = this.data_.insert(hint, key); - - // POST-PROCESS - this._Handle_insert(it, it.next()); - - return it; - } - - protected _Insert_by_range< - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void { - // INSERT ELEMENTS - const my_first = this.data_.insert(this.data_.end(), first, last); - - // IF NEEDED, HASH_BUCKET TO HAVE SUITABLE SIZE - if (this.size() > this.buckets_.capacity()) - this.reserve(Math.max(this.size(), this.buckets_.capacity() * 2)); - - // POST-PROCESS - this._Handle_insert(my_first, this.end()); - } - - /* --------------------------------------------------------- + protected _Insert_by_key(key: Key): HashMultiSet.Iterator { + // INSERT + const it = this.data_.insert(this.data_.end(), key); + + this._Handle_insert(it, it.next()); // POST-PROCESS + return it; + } + + protected _Insert_by_hint( + hint: HashMultiSet.Iterator, + key: Key, + ): HashMultiSet.Iterator { + // INSERT + const it = this.data_.insert(hint, key); + + // POST-PROCESS + this._Handle_insert(it, it.next()); + + return it; + } + + protected _Insert_by_range< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void { + // INSERT ELEMENTS + const my_first = this.data_.insert(this.data_.end(), first, last); + + // IF NEEDED, HASH_BUCKET TO HAVE SUITABLE SIZE + if (this.size() > this.buckets_.capacity()) + this.reserve(Math.max(this.size(), this.buckets_.capacity() * 2)); + + // POST-PROCESS + this._Handle_insert(my_first, this.end()); + } + + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert( - first: HashMultiSet.Iterator, - last: HashMultiSet.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.buckets_.insert(first); - } - - protected _Handle_erase( - first: HashMultiSet.Iterator, - last: HashMultiSet.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.buckets_.erase(first); - } + protected _Handle_insert( + first: HashMultiSet.Iterator, + last: HashMultiSet.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) + this.buckets_.insert(first); + } + + protected _Handle_erase( + first: HashMultiSet.Iterator, + last: HashMultiSet.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) + this.buckets_.erase(first); + } } /** * */ export namespace HashMultiSet { - // HEAD - /** - * Iterator of {@link HashMultiSet} - */ - export type Iterator = SetElementList.Iterator< - Key, - false, - HashMultiSet - >; - - /** - * Reverse iterator of {@link HashMultiSet} - */ - export type ReverseIterator = SetElementList.ReverseIterator< - Key, - false, - HashMultiSet - >; - - // BODY - export const Iterator = SetElementList.Iterator; - export const ReverseIterator = SetElementList.ReverseIterator; + // HEAD + /** + * Iterator of {@link HashMultiSet} + */ + export type Iterator = SetElementList.Iterator< + Key, + false, + HashMultiSet + >; + + /** + * Reverse iterator of {@link HashMultiSet} + */ + export type ReverseIterator = SetElementList.ReverseIterator< + Key, + false, + HashMultiSet + >; + + // BODY + export const Iterator = SetElementList.Iterator; + export const ReverseIterator = SetElementList.ReverseIterator; } diff --git a/src/container/HashSet.ts b/src/container/HashSet.ts index a991b96a..d25151fb 100644 --- a/src/container/HashSet.ts +++ b/src/container/HashSet.ts @@ -1,22 +1,20 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { UniqueSet } from "../base/container/UniqueSet"; import { IHashSet } from "../base/container/IHashSet"; +import { UniqueSet } from "../base/container/UniqueSet"; import { IHashContainer } from "../internal/container/associative/IHashContainer"; - import { SetElementList } from "../internal/container/associative/SetElementList"; -import { SetHashBuckets } from "../internal/hash/SetHashBuckets"; - -import { IForwardIterator } from "../iterator/IForwardIterator"; -import { Pair } from "../utility/Pair"; - import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; import { Hasher } from "../internal/functional/Hasher"; import { Temporary } from "../internal/functional/Temporary"; +import { SetHashBuckets } from "../internal/hash/SetHashBuckets"; +import { IForwardIterator } from "../iterator/IForwardIterator"; +import { Pair } from "../utility/Pair"; /** * Unique-key Set based on Hash buckets. @@ -24,253 +22,253 @@ import { Temporary } from "../internal/functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export class HashSet - extends UniqueSet< - Key, - HashSet, - HashSet.Iterator, - HashSet.ReverseIterator - > - implements IHashSet> + extends UniqueSet< + Key, + HashSet, + HashSet.Iterator, + HashSet.ReverseIterator + > + implements IHashSet> { - private buckets_!: SetHashBuckets>; + private buckets_!: SetHashBuckets>; - /* ========================================================= + /* ========================================================= CONSTRUCTORS & SEMI-CONSTRUCTORS - CONSTRUCTORS - ASSIGN & CLEAR ============================================================ CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor(hash?: Hasher, equal?: BinaryPredicator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor( - items: Key[], - hash?: Hasher, - equal?: BinaryPredicator, - ); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: HashSet); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param hash An unary function returns hash code. Default is {hash}. - * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - public constructor( - first: Readonly>, - last: Readonly>, - hash?: Hasher, - equal?: BinaryPredicator, + /** + * Default Constructor. + * + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor(hash?: Hasher, equal?: BinaryPredicator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor( + items: Key[], + hash?: Hasher, + equal?: BinaryPredicator, + ); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: HashSet); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param hash An unary function returns hash code. Default is {hash}. + * @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + public constructor( + first: Readonly>, + last: Readonly>, + hash?: Hasher, + equal?: BinaryPredicator, + ); + + public constructor(...args: any[]) { + super((thisArg) => new SetElementList(thisArg)); + + IHashContainer.construct< + Key, + Key, + HashSet, + HashSet.Iterator, + HashSet.ReverseIterator, + Key + >( + this, + HashSet, + (hash, pred) => { + this.buckets_ = new SetHashBuckets(this, hash, pred); + }, + ...args, ); + } - public constructor(...args: any[]) { - super((thisArg) => new SetElementList(thisArg)); - - IHashContainer.construct< - Key, - Key, - HashSet, - HashSet.Iterator, - HashSet.ReverseIterator, - Key - >( - this, - HashSet, - (hash, pred) => { - this.buckets_ = new SetHashBuckets(this, hash, pred); - }, - ...args, - ); - } - - /* --------------------------------------------------------- + /* --------------------------------------------------------- ASSIGN & CLEAR --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public clear(): void { - this.buckets_.clear(); - - super.clear(); - } + /** + * @inheritDoc + */ + public clear(): void { + this.buckets_.clear(); + + super.clear(); + } + + /** + * @inheritDoc + */ + public swap(obj: HashSet): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + SetElementList._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, + ); - /** - * @inheritDoc - */ - public swap(obj: HashSet): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - SetElementList._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP BUCKETS - SetHashBuckets._Swap_source(this.buckets_, obj.buckets_); - [this.buckets_, obj.buckets_] = [obj.buckets_, this.buckets_]; - } + // SWAP BUCKETS + SetHashBuckets._Swap_source(this.buckets_, obj.buckets_); + [this.buckets_, obj.buckets_] = [obj.buckets_, this.buckets_]; + } - /* ========================================================= + /* ========================================================= ACCESSORS - MEMBER - HASH ============================================================ MEMBER --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public find(key: Key): HashSet.Iterator { - return this.buckets_.find(key); - } - - /** - * @inheritDoc - */ - public begin(): HashSet.Iterator; - /** - * @inheritDoc - */ - public begin(index: number): HashSet.Iterator; - public begin(index: number | null = null): HashSet.Iterator { - if (index === null) return super.begin(); - else return this.buckets_.at(index)[0]; - } - - /** - * @inheritDoc - */ - public end(): HashSet.Iterator; - /** - * @inheritDoc - */ - public end(index: number): HashSet.Iterator; - public end(index: number | null = null): HashSet.Iterator { - if (index === null) return super.end(); - else { - const bucket = this.buckets_.at(index); - return bucket[bucket.length - 1].next(); - } - } - - /** - * @inheritDoc - */ - public rbegin(): HashSet.ReverseIterator; - /** - * @inheritDoc - */ - public rbegin(index: number): HashSet.ReverseIterator; - public rbegin(index: number | null = null): HashSet.ReverseIterator { - return this.end(index!).reverse(); - } - - /** - * @inheritDoc - */ - public rend(): HashSet.ReverseIterator; - /** - * @inheritDoc - */ - public rend(index: number): HashSet.ReverseIterator; - public rend(index: number | null = null): HashSet.ReverseIterator { - return this.begin(index!).reverse(); + /** + * @inheritDoc + */ + public find(key: Key): HashSet.Iterator { + return this.buckets_.find(key); + } + + /** + * @inheritDoc + */ + public begin(): HashSet.Iterator; + /** + * @inheritDoc + */ + public begin(index: number): HashSet.Iterator; + public begin(index: number | null = null): HashSet.Iterator { + if (index === null) return super.begin(); + else return this.buckets_.at(index)[0]; + } + + /** + * @inheritDoc + */ + public end(): HashSet.Iterator; + /** + * @inheritDoc + */ + public end(index: number): HashSet.Iterator; + public end(index: number | null = null): HashSet.Iterator { + if (index === null) return super.end(); + else { + const bucket = this.buckets_.at(index); + return bucket[bucket.length - 1].next(); } - - /* --------------------------------------------------------- + } + + /** + * @inheritDoc + */ + public rbegin(): HashSet.ReverseIterator; + /** + * @inheritDoc + */ + public rbegin(index: number): HashSet.ReverseIterator; + public rbegin(index: number | null = null): HashSet.ReverseIterator { + return this.end(index!).reverse(); + } + + /** + * @inheritDoc + */ + public rend(): HashSet.ReverseIterator; + /** + * @inheritDoc + */ + public rend(index: number): HashSet.ReverseIterator; + public rend(index: number | null = null): HashSet.ReverseIterator { + return this.begin(index!).reverse(); + } + + /* --------------------------------------------------------- HASH --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public bucket_count(): number { - return this.buckets_.length(); - } - - /** - * @inheritDoc - */ - public bucket_size(n: number): number { - return this.buckets_.at(n).length; - } - - /** - * @inheritDoc - */ - public load_factor(): number { - return this.buckets_.load_factor(); - } - - /** - * @inheritDoc - */ - public hash_function(): Hasher { - return this.buckets_.hash_function(); - } - - /** - * @inheritDoc - */ - public key_eq(): BinaryPredicator { - return this.buckets_.key_eq(); - } - - /** - * @inheritDoc - */ - public bucket(key: Key): number { - return this.hash_function()(key) % this.buckets_.length(); - } - - /** - * @inheritDoc - */ - public max_load_factor(): number; - /** - * @inheritDoc - */ - public max_load_factor(z: number): void; - public max_load_factor(z: number | null = null): any { - return this.buckets_.max_load_factor(z!); - } - - /** - * @inheritDoc - */ - public reserve(n: number): void { - this.buckets_.reserve(n); - } - - /** - * @inheritDoc - */ - public rehash(n: number): void { - this.buckets_.rehash(n); - } - - /* ========================================================= + /** + * @inheritDoc + */ + public bucket_count(): number { + return this.buckets_.length(); + } + + /** + * @inheritDoc + */ + public bucket_size(n: number): number { + return this.buckets_.at(n).length; + } + + /** + * @inheritDoc + */ + public load_factor(): number { + return this.buckets_.load_factor(); + } + + /** + * @inheritDoc + */ + public hash_function(): Hasher { + return this.buckets_.hash_function(); + } + + /** + * @inheritDoc + */ + public key_eq(): BinaryPredicator { + return this.buckets_.key_eq(); + } + + /** + * @inheritDoc + */ + public bucket(key: Key): number { + return this.hash_function()(key) % this.buckets_.length(); + } + + /** + * @inheritDoc + */ + public max_load_factor(): number; + /** + * @inheritDoc + */ + public max_load_factor(z: number): void; + public max_load_factor(z: number | null = null): any { + return this.buckets_.max_load_factor(z!); + } + + /** + * @inheritDoc + */ + public reserve(n: number): void { + this.buckets_.reserve(n); + } + + /** + * @inheritDoc + */ + public rehash(n: number): void { + this.buckets_.rehash(n); + } + + /* ========================================================= ELEMENTS I/O - INSERT - POST-PROCESS @@ -278,81 +276,77 @@ export class HashSet ============================================================ INSERT --------------------------------------------------------- */ - protected _Insert_by_key(key: Key): Pair, boolean> { - // TEST WHETHER EXIST - let it: HashSet.Iterator = this.find(key); - if (it.equals(this.end()) === false) return new Pair(it, false); - - // INSERT - this.data_.push(key); - it = it.prev(); - - // POST-PROCESS - this._Handle_insert(it, it.next()); - - return new Pair(it, true); - } - - protected _Insert_by_hint( - hint: HashSet.Iterator, - key: Key, - ): HashSet.Iterator { - // FIND DUPLICATED KEY - let it: HashSet.Iterator = this.find(key); - if (it.equals(this.end()) === true) { - // INSERT - it = this.data_.insert(hint, key); - - // POST-PROCESS - this._Handle_insert(it, it.next()); - } - return it; + protected _Insert_by_key(key: Key): Pair, boolean> { + // TEST WHETHER EXIST + let it: HashSet.Iterator = this.find(key); + if (it.equals(this.end()) === false) return new Pair(it, false); + + // INSERT + this.data_.push(key); + it = it.prev(); + + // POST-PROCESS + this._Handle_insert(it, it.next()); + + return new Pair(it, true); + } + + protected _Insert_by_hint( + hint: HashSet.Iterator, + key: Key, + ): HashSet.Iterator { + // FIND DUPLICATED KEY + let it: HashSet.Iterator = this.find(key); + if (it.equals(this.end()) === true) { + // INSERT + it = this.data_.insert(hint, key); + + // POST-PROCESS + this._Handle_insert(it, it.next()); } + return it; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert( - first: HashSet.Iterator, - last: HashSet.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.buckets_.insert(first); - } - - protected _Handle_erase( - first: HashSet.Iterator, - last: HashSet.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.buckets_.erase(first); - } + protected _Handle_insert( + first: HashSet.Iterator, + last: HashSet.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) + this.buckets_.insert(first); + } + + protected _Handle_erase( + first: HashSet.Iterator, + last: HashSet.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) + this.buckets_.erase(first); + } } /** * */ export namespace HashSet { - // HEAD - /** - * Iterator of {@link HashSet} - */ - export type Iterator = SetElementList.Iterator< - Key, - true, - HashSet - >; - - /** - * Reverse iterator of {@link HashSet} - */ - export type ReverseIterator = SetElementList.ReverseIterator< - Key, - true, - HashSet - >; - - // BODY - export const Iterator = SetElementList.Iterator; - export const ReverseIterator = SetElementList.ReverseIterator; + // HEAD + /** + * Iterator of {@link HashSet} + */ + export type Iterator = SetElementList.Iterator>; + + /** + * Reverse iterator of {@link HashSet} + */ + export type ReverseIterator = SetElementList.ReverseIterator< + Key, + true, + HashSet + >; + + // BODY + export const Iterator = SetElementList.Iterator; + export const ReverseIterator = SetElementList.ReverseIterator; } diff --git a/src/container/List.ts b/src/container/List.ts index 276a248d..61552b33 100644 --- a/src/container/List.ts +++ b/src/container/List.ts @@ -1,23 +1,21 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { ListContainer } from "../internal/container/linear/ListContainer"; import { IDequeContainer } from "../base/container/IDequeContainer"; -import { IListAlgorithm } from "../internal/container/linear/IListAlgorithm"; - -import { ListIterator } from "../internal/iterator/ListIterator"; -import { ReverseIterator as ReverseIteratorBase } from "../internal/iterator/ReverseIterator"; - import { IPointer } from "../functional/IPointer"; -import { IForwardIterator } from "../iterator/IForwardIterator"; import { equal_to, less } from "../functional/comparators"; - +import { IListAlgorithm } from "../internal/container/linear/IListAlgorithm"; +import { ListContainer } from "../internal/container/linear/ListContainer"; import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; import { Comparator } from "../internal/functional/Comparator"; import { UnaryPredicator } from "../internal/functional/UnaryPredicator"; +import { ListIterator } from "../internal/iterator/ListIterator"; +import { ReverseIterator as ReverseIteratorBase } from "../internal/iterator/ReverseIterator"; +import { IForwardIterator } from "../iterator/IForwardIterator"; /** * Doubly Linked List. @@ -25,132 +23,132 @@ import { UnaryPredicator } from "../internal/functional/UnaryPredicator"; * @author Jeongho Nam - https://github.com/samchon */ export class List - extends ListContainer, List.Iterator, List.ReverseIterator> - implements - IDequeContainer, List.Iterator, List.ReverseIterator>, - IListAlgorithm> + extends ListContainer, List.Iterator, List.ReverseIterator> + implements + IDequeContainer, List.Iterator, List.ReverseIterator>, + IListAlgorithm> { - private ptr_: IPointer>; + private ptr_: IPointer>; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor(); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - */ - public constructor(items: Array); - - /** - * Copy Constructor - * - * @param obj Object to copy. - */ - public constructor(obj: List); - - /** - * Fill Constructor. - * - * @param size Initial size. - * @param val Value to fill. - */ - public constructor(size: number, val: T); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iteartor of the last position. - */ - public constructor( - first: Readonly>, - last: Readonly>, - ); - - public constructor(...args: any[]) { - //---- - // DEFAULT CONFIGURATIONS - //---- - // INHERITS - super(); - - // DECLARE SOURCE POINTER - this.ptr_ = { value: this }; - List.Iterator._Set_source_ptr(this.end_, this.ptr_); - - //---- - // BRANCHES - //---- - if (args.length === 0) { - // DEFAULT CONSTRUCTOR - } else if (args.length === 1 && args[0] instanceof Array) { - // INITIALIZER CONSTRUCTOR - const array: Array = args[0]; - this.push(...array); - } else if (args.length === 1 && args[0] instanceof List) { - // COPY CONSTRUCTOR - const container: List = args[0]; - this.assign(container.begin(), container.end()); - } else if (args.length === 2) { - // ASSIGN CONTRUCTOR - this.assign(args[0], args[1]); - } - } - - protected _Create_iterator( - prev: List.Iterator, - next: List.Iterator, - val: T, - ): List.Iterator { - return List.Iterator.create( - this.ptr_, - prev as List.Iterator, - next as List.Iterator, - val, - ); + /** + * Default Constructor. + */ + public constructor(); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + */ + public constructor(items: Array); + + /** + * Copy Constructor + * + * @param obj Object to copy. + */ + public constructor(obj: List); + + /** + * Fill Constructor. + * + * @param size Initial size. + * @param val Value to fill. + */ + public constructor(size: number, val: T); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iteartor of the last position. + */ + public constructor( + first: Readonly>, + last: Readonly>, + ); + + public constructor(...args: any[]) { + //---- + // DEFAULT CONFIGURATIONS + //---- + // INHERITS + super(); + + // DECLARE SOURCE POINTER + this.ptr_ = { value: this }; + List.Iterator._Set_source_ptr(this.end_, this.ptr_); + + //---- + // BRANCHES + //---- + if (args.length === 0) { + // DEFAULT CONSTRUCTOR + } else if (args.length === 1 && args[0] instanceof Array) { + // INITIALIZER CONSTRUCTOR + const array: Array = args[0]; + this.push(...array); + } else if (args.length === 1 && args[0] instanceof List) { + // COPY CONSTRUCTOR + const container: List = args[0]; + this.assign(container.begin(), container.end()); + } else if (args.length === 2) { + // ASSIGN CONTRUCTOR + this.assign(args[0], args[1]); } + } + + protected _Create_iterator( + prev: List.Iterator, + next: List.Iterator, + val: T, + ): List.Iterator { + return List.Iterator.create( + this.ptr_, + prev as List.Iterator, + next as List.Iterator, + val, + ); + } - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- DEQUE ACCESSORS --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public front(): T; - - /** - * @inheritDoc - */ - public front(val: T): void; - - public front(val?: T): T | void { - if (arguments.length === 0) return this.begin_.value; - else this.begin_.value = val!; - } - - /** - * @inheritDoc - */ - public back(): T; - - /** - * @inheritDoc - */ - public back(val: T): void; - - public back(val?: T): T | void { - const it = this.end().prev(); - if (arguments.length === 0) return it.value; - else it.value = val!; - } - - /* =============================================================== + /** + * @inheritDoc + */ + public front(): T; + + /** + * @inheritDoc + */ + public front(val: T): void; + + public front(val?: T): T | void { + if (arguments.length === 0) return this.begin_.value; + else this.begin_.value = val!; + } + + /** + * @inheritDoc + */ + public back(): T; + + /** + * @inheritDoc + */ + public back(val: T): void; + + public back(val?: T): T | void { + const it = this.end().prev(); + if (arguments.length === 0) return it.value; + else it.value = val!; + } + + /* =============================================================== ALGORITHMS - UNIQUE & REMOVE(_IF) - MERGE & SPLICE @@ -158,327 +156,323 @@ export class List ================================================================== UNIQUE & REMOVE(_IF) --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public unique(binary_pred: BinaryPredicator = equal_to): void { - let it = this.begin().next(); - - while (!it.equals(this.end())) { - if (binary_pred(it.value, it.prev().value) === true) - it = this.erase(it); - else it = it.next(); - } + /** + * @inheritDoc + */ + public unique(binary_pred: BinaryPredicator = equal_to): void { + let it = this.begin().next(); + + while (!it.equals(this.end())) { + if (binary_pred(it.value, it.prev().value) === true) it = this.erase(it); + else it = it.next(); + } + } + + /** + * @inheritDoc + */ + public remove(val: T): void { + return this.remove_if((elem) => equal_to(elem, val)); + } + + /** + * @inheritDoc + */ + public remove_if(pred: UnaryPredicator): void { + let it = this.begin(); + + while (!it.equals(this.end())) { + if (pred(it.value) === true) it = this.erase(it); + else it = it.next(); } + } - /** - * @inheritDoc - */ - public remove(val: T): void { - return this.remove_if((elem) => equal_to(elem, val)); + /* --------------------------------------------------------- + MERGE & SPLICE + --------------------------------------------------------- */ + /** + * @inheritDoc + */ + public merge(source: List, comp: Comparator = less): void { + if (this === >source) return; + + let it = this.begin(); + while (source.empty() === false) { + const first = source.begin(); + while (!it.equals(this.end()) && comp(it.value, first.value) === true) + it = it.next(); + + this.splice(it, source, first); + } + } + + /** + * Transfer elements. + * + * @param pos Position to insert. + * @param from Target container to transfer. + */ + public splice(pos: List.Iterator, from: List): void; + + /** + * Transfer a single element. + * + * @param pos Position to insert. + * @param from Target container to transfer. + * @param it Position of the single element to transfer. + */ + public splice( + pos: List.Iterator, + from: List, + it: List.Iterator, + ): void; + + /** + * Transfer range elements. + * + * @param pos Position to insert. + * @param from Target container to transfer. + * @param first Range of the first position to transfer. + * @param last Rangee of the last position to transfer. + */ + public splice( + pos: List.Iterator, + from: List, + first: List.Iterator, + last: List.Iterator, + ): void; + + public splice( + pos: List.Iterator, + obj: List, + first?: List.Iterator, + last?: List.Iterator, + ): void { + if (first === undefined) { + first = obj.begin(); + last = obj.end(); + } else if (last === undefined) last = first.next(); + + this.insert(pos, first, last); + obj.erase(first, last); + } + + /* --------------------------------------------------------- + SORT & SWAP + --------------------------------------------------------- */ + /** + * @inheritDoc + */ + public sort(comp: Comparator = less): void { + this._Quick_sort(this.begin(), this.end().prev(), comp); + } + + private _Quick_sort( + first: List.Iterator, + last: List.Iterator, + comp: Comparator, + ): void { + if ( + !first.equals(last) && + !last.equals(this.end()) && + !first.equals(last.next()) + ) { + const temp: List.Iterator = this._Quick_sort_partition( + first, + last, + comp, + ); + + this._Quick_sort(first, temp.prev(), comp); + this._Quick_sort(temp.next(), last, comp); } + } + + private _Quick_sort_partition( + first: List.Iterator, + last: List.Iterator, + comp: Comparator, + ): List.Iterator { + const standard: T = last.value; // TO BE COMPARED + let prev: List.Iterator = first.prev(); // TO BE SMALLEST + + let it: List.Iterator = first; + for (; !it.equals(last); it = it.next()) + if (comp(it.value, standard)) { + prev = prev.equals(this.end()) ? first : prev.next(); + [prev.value, it.value] = [it.value, prev.value]; + } - /** - * @inheritDoc - */ - public remove_if(pred: UnaryPredicator): void { - let it = this.begin(); + prev = prev.equals(this.end()) ? first : prev.next(); + [prev.value, it.value] = [it.value, prev.value]; + + return prev; + } + + /** + * @inheritDoc + */ + public reverse(): void { + const begin: List.Iterator = this.end_.prev(); + const prev_of_end: List.Iterator = this.begin(); + + for (let it = this.begin(); !it.equals(this.end()); ) { + const prev = it.prev(); + const next = it.next(); + + List.Iterator._Set_prev(it, next); + List.Iterator._Set_next(it, prev); - while (!it.equals(this.end())) { - if (pred(it.value) === true) it = this.erase(it); - else it = it.next(); - } + it = next; } - /* --------------------------------------------------------- - MERGE & SPLICE - --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public merge(source: List, comp: Comparator = less): void { - if (this === >source) return; - - let it = this.begin(); - while (source.empty() === false) { - const first = source.begin(); - while ( - !it.equals(this.end()) && - comp(it.value, first.value) === true - ) - it = it.next(); - - this.splice(it, source, first); - } + // ADJUST THE BEGIN AND END + this.begin_ = begin; // THE NEW BEGIN + List.Iterator._Set_prev(this.end_, prev_of_end); + List.Iterator._Set_next(this.end_, begin); + } + + /** + * @inheritDoc + */ + public swap(obj: List): void { + // CHANGE CONTENTS + super.swap(obj); + + // CHANGE ITERATORS' SOURCES + [this.ptr_, obj.ptr_] = [obj.ptr_, this.ptr_]; + [this.ptr_.value, obj.ptr_.value] = [obj.ptr_.value, this.ptr_.value]; + } +} + +/** + * + */ +export namespace List { + /** + * Iterator of {@link List} + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class Iterator extends ListIterator< + T, + List, + Iterator, + ReverseIterator, + T + > { + private source_ptr_: IPointer>; + + /* --------------------------------------------------------------- + CONSTRUCTORS + --------------------------------------------------------------- */ + private constructor( + sourcePtr: IPointer>, + prev: Iterator, + next: Iterator, + value: T, + ) { + super(prev, next, value); + this.source_ptr_ = sourcePtr; } /** - * Transfer elements. - * - * @param pos Position to insert. - * @param from Target container to transfer. + * @internal */ - public splice(pos: List.Iterator, from: List): void; + public static create( + sourcePtr: IPointer>, + prev: Iterator, + next: Iterator, + value: T, + ) { + return new Iterator(sourcePtr, prev, next, value); + } /** - * Transfer a single element. - * - * @param pos Position to insert. - * @param from Target container to transfer. - * @param it Position of the single element to transfer. + * @inheritDoc */ - public splice( - pos: List.Iterator, - from: List, - it: List.Iterator, - ): void; + public reverse(): ReverseIterator { + return new ReverseIterator(this); + } /** - * Transfer range elements. - * - * @param pos Position to insert. - * @param from Target container to transfer. - * @param first Range of the first position to transfer. - * @param last Rangee of the last position to transfer. + * @internal */ - public splice( - pos: List.Iterator, - from: List, - first: List.Iterator, - last: List.Iterator, - ): void; - - public splice( - pos: List.Iterator, - obj: List, - first?: List.Iterator, - last?: List.Iterator, + public static _Set_source_ptr( + it: Iterator, + ptr: IPointer>, ): void { - if (first === undefined) { - first = obj.begin(); - last = obj.end(); - } else if (last === undefined) last = first.next(); - - this.insert(pos, first, last); - obj.erase(first, last); + it.source_ptr_ = ptr; } - /* --------------------------------------------------------- - SORT & SWAP - --------------------------------------------------------- */ + /* --------------------------------------------------------------- + ACCESSORS + --------------------------------------------------------------- */ /** * @inheritDoc */ - public sort(comp: Comparator = less): void { - this._Quick_sort(this.begin(), this.end().prev(), comp); - } - - private _Quick_sort( - first: List.Iterator, - last: List.Iterator, - comp: Comparator, - ): void { - if ( - !first.equals(last) && - !last.equals(this.end()) && - !first.equals(last.next()) - ) { - const temp: List.Iterator = this._Quick_sort_partition( - first, - last, - comp, - ); - - this._Quick_sort(first, temp.prev(), comp); - this._Quick_sort(temp.next(), last, comp); - } - } - - private _Quick_sort_partition( - first: List.Iterator, - last: List.Iterator, - comp: Comparator, - ): List.Iterator { - const standard: T = last.value; // TO BE COMPARED - let prev: List.Iterator = first.prev(); // TO BE SMALLEST - - let it: List.Iterator = first; - for (; !it.equals(last); it = it.next()) - if (comp(it.value, standard)) { - prev = prev.equals(this.end()) ? first : prev.next(); - [prev.value, it.value] = [it.value, prev.value]; - } - - prev = prev.equals(this.end()) ? first : prev.next(); - [prev.value, it.value] = [it.value, prev.value]; - - return prev; + public source(): List { + return this.source_ptr_.value; } /** * @inheritDoc */ - public reverse(): void { - const begin: List.Iterator = this.end_.prev(); - const prev_of_end: List.Iterator = this.begin(); - - for (let it = this.begin(); !it.equals(this.end()); ) { - const prev = it.prev(); - const next = it.next(); - - List.Iterator._Set_prev(it, next); - List.Iterator._Set_next(it, prev); - - it = next; - } - - // ADJUST THE BEGIN AND END - this.begin_ = begin; // THE NEW BEGIN - List.Iterator._Set_prev(this.end_, prev_of_end); - List.Iterator._Set_next(this.end_, begin); + public get value(): T { + this._Try_value(); + return this.value_; } /** * @inheritDoc */ - public swap(obj: List): void { - // CHANGE CONTENTS - super.swap(obj); - - // CHANGE ITERATORS' SOURCES - [this.ptr_, obj.ptr_] = [obj.ptr_, this.ptr_]; - [this.ptr_.value, obj.ptr_.value] = [obj.ptr_.value, this.ptr_.value]; + public set value(val: T) { + this._Try_value(); + this.value_ = val; } -} -/** - * - */ -export namespace List { - /** - * Iterator of {@link List} - * - * @author Jeongho Nam - https://github.com/samchon - */ - export class Iterator extends ListIterator< - T, - List, - Iterator, - ReverseIterator, - T - > { - private source_ptr_: IPointer>; - - /* --------------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------------- */ - private constructor( - sourcePtr: IPointer>, - prev: Iterator, - next: Iterator, - value: T, - ) { - super(prev, next, value); - this.source_ptr_ = sourcePtr; - } - - /** - * @internal - */ - public static create( - sourcePtr: IPointer>, - prev: Iterator, - next: Iterator, - value: T, - ) { - return new Iterator(sourcePtr, prev, next, value); - } - - /** - * @inheritDoc - */ - public reverse(): ReverseIterator { - return new ReverseIterator(this); - } - - /** - * @internal - */ - public static _Set_source_ptr( - it: Iterator, - ptr: IPointer>, - ): void { - it.source_ptr_ = ptr; - } - - /* --------------------------------------------------------------- - ACCESSORS - --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public source(): List { - return this.source_ptr_.value; - } - - /** - * @inheritDoc - */ - public get value(): T { - this._Try_value(); - return this.value_; - } - - /** - * @inheritDoc - */ - public set value(val: T) { - this._Try_value(); - this.value_ = val; - } - - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- COMPARISON --------------------------------------------------------------- */ - public equals(obj: Iterator): boolean { - return this === obj; - } + public equals(obj: Iterator): boolean { + return this === obj; } - - /** - * Reverse iterator of {@link List} - * - * @author Jeongho Nam - https://github.com/samchon - */ - export class ReverseIterator extends ReverseIteratorBase< - T, - List, - Iterator, - ReverseIterator, - T - > { - /* --------------------------------------------------------------- + } + + /** + * Reverse iterator of {@link List} + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class ReverseIterator extends ReverseIteratorBase< + T, + List, + Iterator, + ReverseIterator, + T + > { + /* --------------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------------- */ - protected _Create_neighbor(base: Iterator): ReverseIterator { - return new ReverseIterator(base); - } + protected _Create_neighbor(base: Iterator): ReverseIterator { + return new ReverseIterator(base); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public get value(): T { - return this.base_.value; - } - - /** - * @inheritDoc - */ - public set value(val: T) { - this.base_.value = val; - } + /** + * @inheritDoc + */ + public get value(): T { + return this.base_.value; + } + + /** + * @inheritDoc + */ + public set value(val: T) { + this.base_.value = val; } + } } diff --git a/src/container/PriorityQueue.ts b/src/container/PriorityQueue.ts index a5812631..76ac63c4 100644 --- a/src/container/PriorityQueue.ts +++ b/src/container/PriorityQueue.ts @@ -1,17 +1,16 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { AdaptorContainer } from "../internal/container/linear/AdaptorContainer"; - -import { Vector } from "./Vector"; -import { IForwardIterator } from "../iterator/IForwardIterator"; import { pop_heap, push_heap } from "../algorithm/heap"; - -import { Comparator } from "../internal/functional/Comparator"; import { less } from "../functional/comparators"; +import { AdaptorContainer } from "../internal/container/linear/AdaptorContainer"; +import { Comparator } from "../internal/functional/Comparator"; +import { IForwardIterator } from "../iterator/IForwardIterator"; +import { Vector } from "./Vector"; /** * Priority Queue; Greater Out First. @@ -19,131 +18,131 @@ import { less } from "../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export class PriorityQueue extends AdaptorContainer< - T, - Vector, - PriorityQueue + T, + Vector, + PriorityQueue > { - private comp_: Comparator; + private comp_: Comparator; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(comp?: Comparator); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: PriorityQueue); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor( - first: Readonly>, - last: Readonly>, - comp?: Comparator, - ); - - public constructor(...args: any[]) { - super(new Vector()); - - // DECLARE MEMBERS - let comp: Comparator = less; - let post_process: (() => void) | null = null; - - //---- - // INITIALIZE MEMBERS AND POST-PROCESS - //---- - // BRANCH - METHOD OVERLOADINGS - if (args.length === 1 && args[0] instanceof PriorityQueue) { - const obj: PriorityQueue = args[0]; - - comp = obj.comp_; - post_process = () => { - const first = obj.source_.begin(); - const last = obj.source_.end(); - - this.source_.assign(first, last); - }; - } else if ( - args.length >= 2 && - args[0].next instanceof Function && - args[1].next instanceof Function - ) { - // FUNCTION TEMPLATE - if (args.length === 3) comp = args[2]; - - post_process = () => { - // RANGE CONSTRUCTOR - const first: Readonly> = args[0]; // PARAMETER 1 - const last: Readonly> = args[1]; // PARAMETER 2 - - this.source_.assign(first, last); - }; - } else if (args.length === 1) comp = args[0]; - - //---- - // DO PROCESS - //---- - this.comp_ = comp; - if (post_process !== null) post_process(); - } - - /* --------------------------------------------------------- + /** + * Default Constructor. + * + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(comp?: Comparator); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: PriorityQueue); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor( + first: Readonly>, + last: Readonly>, + comp?: Comparator, + ); + + public constructor(...args: any[]) { + super(new Vector()); + + // DECLARE MEMBERS + let comp: Comparator = less; + let post_process: (() => void) | null = null; + + //---- + // INITIALIZE MEMBERS AND POST-PROCESS + //---- + // BRANCH - METHOD OVERLOADINGS + if (args.length === 1 && args[0] instanceof PriorityQueue) { + const obj: PriorityQueue = args[0]; + + comp = obj.comp_; + post_process = () => { + const first = obj.source_.begin(); + const last = obj.source_.end(); + + this.source_.assign(first, last); + }; + } else if ( + args.length >= 2 && + args[0].next instanceof Function && + args[1].next instanceof Function + ) { + // FUNCTION TEMPLATE + if (args.length === 3) comp = args[2]; + + post_process = () => { + // RANGE CONSTRUCTOR + const first: Readonly> = args[0]; // PARAMETER 1 + const last: Readonly> = args[1]; // PARAMETER 2 + + this.source_.assign(first, last); + }; + } else if (args.length === 1) comp = args[0]; + + //---- + // DO PROCESS + //---- + this.comp_ = comp; + if (post_process !== null) post_process(); + } + + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * Get value comparison function. - */ - public value_comp(): Comparator { - return this.comp_; - } - - /** - * Get top element. - */ - public top(): T { - return this.source_.front(); - } - - /* --------------------------------------------------------- + /** + * Get value comparison function. + */ + public value_comp(): Comparator { + return this.comp_; + } + + /** + * Get top element. + */ + public top(): T { + return this.source_.front(); + } + + /* --------------------------------------------------------- ELEMENTS I/O --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public push(...elems: T[]): number { - for (const elem of elems) { - this.source_.push_back(elem); - push_heap(this.source_.begin(), this.source_.end(), this.comp_); - } - return this.size(); - } - - /** - * @inheritDoc - */ - public pop(): void { - pop_heap(this.source_.begin(), this.source_.end(), this.comp_); - this.source_.pop_back(); - } - - /** - * @inheritDoc - */ - public swap(obj: PriorityQueue): void { - super.swap(obj); - [this.comp_, obj.comp_] = [obj.comp_, this.comp_]; + /** + * @inheritDoc + */ + public push(...elems: T[]): number { + for (const elem of elems) { + this.source_.push_back(elem); + push_heap(this.source_.begin(), this.source_.end(), this.comp_); } + return this.size(); + } + + /** + * @inheritDoc + */ + public pop(): void { + pop_heap(this.source_.begin(), this.source_.end(), this.comp_); + this.source_.pop_back(); + } + + /** + * @inheritDoc + */ + public swap(obj: PriorityQueue): void { + super.swap(obj); + [this.comp_, obj.comp_] = [obj.comp_, this.comp_]; + } } diff --git a/src/container/Queue.ts b/src/container/Queue.ts index 1bc89436..e428de43 100644 --- a/src/container/Queue.ts +++ b/src/container/Queue.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -13,53 +14,53 @@ import { List } from "./List"; * @author Jeongho Nam - https://github.com/samchon */ export class Queue extends AdaptorContainer, Queue> { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor(); + /** + * Default Constructor. + */ + public constructor(); - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: Queue); + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: Queue); - public constructor(obj?: Queue) { - super(new List()); + public constructor(obj?: Queue) { + super(new List()); - if (obj !== undefined) - this.source_.assign(obj.source_.begin(), obj.source_.end()); - } + if (obj !== undefined) + this.source_.assign(obj.source_.begin(), obj.source_.end()); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * Get the first element. - * - * @return The first element. - */ - public front(): T { - return this.source_.front(); - } + /** + * Get the first element. + * + * @return The first element. + */ + public front(): T { + return this.source_.front(); + } - /** - * Get the last element. - * - * @return The last element. - */ - public back(): T { - return this.source_.back(); - } + /** + * Get the last element. + * + * @return The last element. + */ + public back(): T { + return this.source_.back(); + } - /** - * @inheritDoc - */ - public pop(): void { - this.source_.pop_front(); - } + /** + * @inheritDoc + */ + public pop(): void { + this.source_.pop_front(); + } } diff --git a/src/container/Stack.ts b/src/container/Stack.ts index b3427144..006cecb9 100644 --- a/src/container/Stack.ts +++ b/src/container/Stack.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -13,44 +14,44 @@ import { Vector } from "./Vector"; * @author Jeongho Nam - https://github.com/samchon */ export class Stack extends AdaptorContainer, Stack> { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor(); + /** + * Default Constructor. + */ + public constructor(); - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: Stack); + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: Stack); - public constructor(obj?: Stack) { - super(new Vector()); + public constructor(obj?: Stack) { + super(new Vector()); - if (obj !== undefined) - this.source_.assign(obj.source_.begin(), obj.source_.end()); - } + if (obj !== undefined) + this.source_.assign(obj.source_.begin(), obj.source_.end()); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSOR --------------------------------------------------------- */ - /** - * Get the last element. - * - * @return The last element. - */ - public top(): T { - return this.source_.back(); - } + /** + * Get the last element. + * + * @return The last element. + */ + public top(): T { + return this.source_.back(); + } - /** - * @inheritDoc - */ - public pop(): void { - this.source_.pop_back(); - } + /** + * @inheritDoc + */ + public pop(): void { + this.source_.pop_back(); + } } diff --git a/src/container/TreeMap.ts b/src/container/TreeMap.ts index ce4143a1..3a8e7b1f 100644 --- a/src/container/TreeMap.ts +++ b/src/container/TreeMap.ts @@ -1,20 +1,19 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { UniqueTreeMap } from "../internal/container/associative/UniqueTreeMap"; import { ITreeContainer } from "../internal/container/associative/ITreeContainer"; - import { MapElementList } from "../internal/container/associative/MapElementList"; -import { UniqueMapTree } from "../internal/tree/UniqueMapTree"; +import { UniqueTreeMap } from "../internal/container/associative/UniqueTreeMap"; import { Comparator } from "../internal/functional/Comparator"; - +import { Temporary } from "../internal/functional/Temporary"; +import { UniqueMapTree } from "../internal/tree/UniqueMapTree"; import { IForwardIterator } from "../iterator/IForwardIterator"; -import { IPair } from "../utility/IPair"; import { Entry } from "../utility/Entry"; -import { Temporary } from "../internal/functional/Temporary"; +import { IPair } from "../utility/IPair"; /** * Unique-key Map based on Tree. @@ -22,169 +21,167 @@ import { Temporary } from "../internal/functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export class TreeMap extends UniqueTreeMap< - Key, - T, - TreeMap, - TreeMap.Iterator, - TreeMap.ReverseIterator + Key, + T, + TreeMap, + TreeMap.Iterator, + TreeMap.ReverseIterator > { - private tree_!: UniqueMapTree>; + private tree_!: UniqueMapTree>; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(comp?: Comparator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(items: IPair[], comp?: Comparator); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: TreeMap); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor( - first: Readonly>>, - last: Readonly>>, - comp?: Comparator, + /** + * Default Constructor. + * + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(comp?: Comparator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(items: IPair[], comp?: Comparator); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: TreeMap); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor( + first: Readonly>>, + last: Readonly>>, + comp?: Comparator, + ); + + public constructor(...args: any[]) { + // INITIALIZATION + super((thisArg) => new MapElementList(thisArg) as Temporary); + + // OVERLOADINGS + ITreeContainer.construct< + Key, + Entry, + TreeMap, + TreeMap.Iterator, + TreeMap.ReverseIterator, + IPair + >( + this, + TreeMap, + (comp) => { + this.tree_ = new UniqueMapTree(this as TreeMap, comp); + }, + ...args, ); + } + + /** + * @inheritDoc + */ + public clear(): void { + super.clear(); + + this.tree_.clear(); + } + + /** + * @inheritDoc + */ + public swap(obj: TreeMap): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + MapElementList._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, + ); + + // SWAP RB-TREE + UniqueMapTree._Swap_source(this.tree_, obj.tree_); + [this.tree_, obj.tree_] = [obj.tree_, this.tree_]; + } - public constructor(...args: any[]) { - // INITIALIZATION - super((thisArg) => new MapElementList(thisArg) as Temporary); - - // OVERLOADINGS - ITreeContainer.construct< - Key, - Entry, - TreeMap, - TreeMap.Iterator, - TreeMap.ReverseIterator, - IPair - >( - this, - TreeMap, - (comp) => { - this.tree_ = new UniqueMapTree(this as TreeMap, comp); - }, - ...args, - ); - } - - /** - * @inheritDoc - */ - public clear(): void { - super.clear(); - - this.tree_.clear(); - } - - /** - * @inheritDoc - */ - public swap(obj: TreeMap): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - MapElementList._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP RB-TREE - UniqueMapTree._Swap_source(this.tree_, obj.tree_); - [this.tree_, obj.tree_] = [obj.tree_, this.tree_]; - } - - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public key_comp(): Comparator { - return this.tree_.key_comp(); - } - - /** - * @inheritDoc - */ - public lower_bound(key: Key): TreeMap.Iterator { - return this.tree_.lower_bound(key); - } - - /** - * @inheritDoc - */ - public upper_bound(key: Key): TreeMap.Iterator { - return this.tree_.upper_bound(key); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public key_comp(): Comparator { + return this.tree_.key_comp(); + } + + /** + * @inheritDoc + */ + public lower_bound(key: Key): TreeMap.Iterator { + return this.tree_.lower_bound(key); + } + + /** + * @inheritDoc + */ + public upper_bound(key: Key): TreeMap.Iterator { + return this.tree_.upper_bound(key); + } + + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert( - first: TreeMap.Iterator, - last: TreeMap.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.tree_.insert(first); - } - - protected _Handle_erase( - first: TreeMap.Iterator, - last: TreeMap.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.tree_.erase(first); - } + protected _Handle_insert( + first: TreeMap.Iterator, + last: TreeMap.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) this.tree_.insert(first); + } + + protected _Handle_erase( + first: TreeMap.Iterator, + last: TreeMap.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) this.tree_.erase(first); + } } /** * */ export namespace TreeMap { - // HEAD - /** - * Iterator of {@link TreeMap} - */ - export type Iterator = MapElementList.Iterator< - Key, - T, - true, - TreeMap - >; - - /** - * Reverse iterator of {@link TreeMap} - */ - export type ReverseIterator = MapElementList.ReverseIterator< - Key, - T, - true, - TreeMap - >; - - // BODY - export const Iterator = MapElementList.Iterator; - export const ReverseIterator = MapElementList.ReverseIterator; + // HEAD + /** + * Iterator of {@link TreeMap} + */ + export type Iterator = MapElementList.Iterator< + Key, + T, + true, + TreeMap + >; + + /** + * Reverse iterator of {@link TreeMap} + */ + export type ReverseIterator = MapElementList.ReverseIterator< + Key, + T, + true, + TreeMap + >; + + // BODY + export const Iterator = MapElementList.Iterator; + export const ReverseIterator = MapElementList.ReverseIterator; } diff --git a/src/container/TreeMultiMap.ts b/src/container/TreeMultiMap.ts index c0e5b426..c78b9ddc 100644 --- a/src/container/TreeMultiMap.ts +++ b/src/container/TreeMultiMap.ts @@ -1,20 +1,19 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { MultiTreeMap } from "../internal/container/associative/MultiTreeMap"; import { ITreeContainer } from "../internal/container/associative/ITreeContainer"; - -import { IForwardIterator } from "../iterator/IForwardIterator"; import { MapElementList } from "../internal/container/associative/MapElementList"; -import { MultiMapTree } from "../internal/tree/MultiMapTree"; +import { MultiTreeMap } from "../internal/container/associative/MultiTreeMap"; import { Comparator } from "../internal/functional/Comparator"; - -import { IPair } from "../utility/IPair"; -import { Entry } from "../utility/Entry"; import { Temporary } from "../internal/functional/Temporary"; +import { MultiMapTree } from "../internal/tree/MultiMapTree"; +import { IForwardIterator } from "../iterator/IForwardIterator"; +import { Entry } from "../utility/Entry"; +import { IPair } from "../utility/IPair"; /** * Multiple-key Map based on Tree. @@ -22,170 +21,165 @@ import { Temporary } from "../internal/functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export class TreeMultiMap extends MultiTreeMap< - Key, - T, - TreeMultiMap, - TreeMultiMap.Iterator, - TreeMultiMap.ReverseIterator + Key, + T, + TreeMultiMap, + TreeMultiMap.Iterator, + TreeMultiMap.ReverseIterator > { - private tree_!: MultiMapTree>; + private tree_!: MultiMapTree>; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(comp?: Comparator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(items: IPair[], comp?: Comparator); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: TreeMultiMap); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor( - first: Readonly>>, - last: Readonly>>, - comp?: Comparator, + /** + * Default Constructor. + * + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(comp?: Comparator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(items: IPair[], comp?: Comparator); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: TreeMultiMap); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor( + first: Readonly>>, + last: Readonly>>, + comp?: Comparator, + ); + + public constructor(...args: any[]) { + super((thisArg) => new MapElementList(thisArg) as Temporary); + + ITreeContainer.construct< + Key, + Entry, + TreeMultiMap, + TreeMultiMap.Iterator, + TreeMultiMap.ReverseIterator, + IPair + >( + this, + TreeMultiMap, + (comp) => { + this.tree_ = new MultiMapTree(this as TreeMultiMap, comp); + }, + ...args, + ); + } + + /** + * @inheritDoc + */ + public clear(): void { + super.clear(); + + this.tree_.clear(); + } + + /** + * @inheritDoc + */ + public swap(obj: TreeMultiMap): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + MapElementList._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, ); - public constructor(...args: any[]) { - super((thisArg) => new MapElementList(thisArg) as Temporary); - - ITreeContainer.construct< - Key, - Entry, - TreeMultiMap, - TreeMultiMap.Iterator, - TreeMultiMap.ReverseIterator, - IPair - >( - this, - TreeMultiMap, - (comp) => { - this.tree_ = new MultiMapTree( - this as TreeMultiMap, - comp, - ); - }, - ...args, - ); - } - - /** - * @inheritDoc - */ - public clear(): void { - super.clear(); - - this.tree_.clear(); - } - - /** - * @inheritDoc - */ - public swap(obj: TreeMultiMap): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - MapElementList._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP RB-TREE - MultiMapTree._Swap_source(this.tree_, obj.tree_); - [this.tree_, obj.tree_] = [obj.tree_, this.tree_]; - } - - /* --------------------------------------------------------- + // SWAP RB-TREE + MultiMapTree._Swap_source(this.tree_, obj.tree_); + [this.tree_, obj.tree_] = [obj.tree_, this.tree_]; + } + + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public key_comp(): Comparator { - return this.tree_.key_comp(); - } - - /** - * @inheritDoc - */ - public lower_bound(key: Key): TreeMultiMap.Iterator { - return this.tree_.lower_bound(key); - } - - /** - * @inheritDoc - */ - public upper_bound(key: Key): TreeMultiMap.Iterator { - return this.tree_.upper_bound(key); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public key_comp(): Comparator { + return this.tree_.key_comp(); + } + + /** + * @inheritDoc + */ + public lower_bound(key: Key): TreeMultiMap.Iterator { + return this.tree_.lower_bound(key); + } + + /** + * @inheritDoc + */ + public upper_bound(key: Key): TreeMultiMap.Iterator { + return this.tree_.upper_bound(key); + } + + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert( - first: TreeMultiMap.Iterator, - last: TreeMultiMap.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.tree_.insert(first); - } - - protected _Handle_erase( - first: TreeMultiMap.Iterator, - last: TreeMultiMap.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.tree_.erase(first); - } + protected _Handle_insert( + first: TreeMultiMap.Iterator, + last: TreeMultiMap.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) this.tree_.insert(first); + } + + protected _Handle_erase( + first: TreeMultiMap.Iterator, + last: TreeMultiMap.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) this.tree_.erase(first); + } } /** * */ export namespace TreeMultiMap { - // HEAD - /** - * Iterator of {@link TreeMultiMap} - */ - export type Iterator = MapElementList.Iterator< - Key, - T, - false, - TreeMultiMap - >; - - /** - * Iterator of {@link TreeMultiMap} - */ - export type ReverseIterator = MapElementList.ReverseIterator< - Key, - T, - false, - TreeMultiMap - >; - - // BODY - export const Iterator = MapElementList.Iterator; - export const ReverseIterator = MapElementList.ReverseIterator; + // HEAD + /** + * Iterator of {@link TreeMultiMap} + */ + export type Iterator = MapElementList.Iterator< + Key, + T, + false, + TreeMultiMap + >; + + /** + * Iterator of {@link TreeMultiMap} + */ + export type ReverseIterator = MapElementList.ReverseIterator< + Key, + T, + false, + TreeMultiMap + >; + + // BODY + export const Iterator = MapElementList.Iterator; + export const ReverseIterator = MapElementList.ReverseIterator; } diff --git a/src/container/TreeMultiSet.ts b/src/container/TreeMultiSet.ts index d432616f..247a6424 100644 --- a/src/container/TreeMultiSet.ts +++ b/src/container/TreeMultiSet.ts @@ -1,18 +1,17 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { MultiTreeSet } from "../internal/container/associative/MultiTreeSet"; import { ITreeContainer } from "../internal/container/associative/ITreeContainer"; - -import { IForwardIterator } from "../iterator/IForwardIterator"; +import { MultiTreeSet } from "../internal/container/associative/MultiTreeSet"; import { SetElementList } from "../internal/container/associative/SetElementList"; -import { MultiSetTree } from "../internal/tree/MultiSetTree"; - import { Comparator } from "../internal/functional/Comparator"; import { Temporary } from "../internal/functional/Temporary"; +import { MultiSetTree } from "../internal/tree/MultiSetTree"; +import { IForwardIterator } from "../iterator/IForwardIterator"; /** * Multiple-key Set based on Tree. @@ -20,164 +19,162 @@ import { Temporary } from "../internal/functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export class TreeMultiSet extends MultiTreeSet< - Key, - TreeMultiSet, - TreeMultiSet.Iterator, - TreeMultiSet.ReverseIterator + Key, + TreeMultiSet, + TreeMultiSet.Iterator, + TreeMultiSet.ReverseIterator > { - private tree_!: MultiSetTree>; + private tree_!: MultiSetTree>; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(comp?: Comparator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(items: Key[], comp?: Comparator); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: TreeMultiSet); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor( - first: Readonly>, - last: Readonly>, - comp?: Comparator, + /** + * Default Constructor. + * + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(comp?: Comparator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(items: Key[], comp?: Comparator); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: TreeMultiSet); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor( + first: Readonly>, + last: Readonly>, + comp?: Comparator, + ); + + public constructor(...args: any[]) { + super((thisArg) => new SetElementList(thisArg) as Temporary); + + ITreeContainer.construct< + Key, + Key, + TreeMultiSet, + TreeMultiSet.Iterator, + TreeMultiSet.ReverseIterator, + Key + >( + this, + TreeMultiSet, + (comp) => { + this.tree_ = new MultiSetTree(this as TreeMultiSet, comp); + }, + ...args, ); + } + + /** + * @inheritDoc + */ + public clear(): void { + super.clear(); + + this.tree_.clear(); + } + + /** + * @inheritDoc + */ + public swap(obj: TreeMultiSet): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + SetElementList._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, + ); + + // SWAP RB-TREE + MultiSetTree._Swap_source(this.tree_, obj.tree_); + [this.tree_, obj.tree_] = [obj.tree_, this.tree_]; + } - public constructor(...args: any[]) { - super((thisArg) => new SetElementList(thisArg) as Temporary); - - ITreeContainer.construct< - Key, - Key, - TreeMultiSet, - TreeMultiSet.Iterator, - TreeMultiSet.ReverseIterator, - Key - >( - this, - TreeMultiSet, - (comp) => { - this.tree_ = new MultiSetTree(this as TreeMultiSet, comp); - }, - ...args, - ); - } - - /** - * @inheritDoc - */ - public clear(): void { - super.clear(); - - this.tree_.clear(); - } - - /** - * @inheritDoc - */ - public swap(obj: TreeMultiSet): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - SetElementList._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP RB-TREE - MultiSetTree._Swap_source(this.tree_, obj.tree_); - [this.tree_, obj.tree_] = [obj.tree_, this.tree_]; - } - - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public key_comp(): Comparator { - return this.tree_.key_comp(); - } - - /** - * @inheritDoc - */ - public lower_bound(key: Key): TreeMultiSet.Iterator { - return this.tree_.lower_bound(key); - } - - /** - * @inheritDoc - */ - public upper_bound(key: Key): TreeMultiSet.Iterator { - return this.tree_.upper_bound(key); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public key_comp(): Comparator { + return this.tree_.key_comp(); + } + + /** + * @inheritDoc + */ + public lower_bound(key: Key): TreeMultiSet.Iterator { + return this.tree_.lower_bound(key); + } + + /** + * @inheritDoc + */ + public upper_bound(key: Key): TreeMultiSet.Iterator { + return this.tree_.upper_bound(key); + } + + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert( - first: TreeMultiSet.Iterator, - last: TreeMultiSet.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.tree_.insert(first); - } - - protected _Handle_erase( - first: TreeMultiSet.Iterator, - last: TreeMultiSet.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.tree_.erase(first); - } + protected _Handle_insert( + first: TreeMultiSet.Iterator, + last: TreeMultiSet.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) this.tree_.insert(first); + } + + protected _Handle_erase( + first: TreeMultiSet.Iterator, + last: TreeMultiSet.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) this.tree_.erase(first); + } } /** * */ export namespace TreeMultiSet { - // HEAD - /** - * Iterator of {@link TreeMultiSet} - */ - export type Iterator = SetElementList.Iterator< - Key, - false, - TreeMultiSet - >; - - /** - * Reverse iterator of {@link TreeMultiSet} - */ - export type ReverseIterator = SetElementList.ReverseIterator< - Key, - false, - TreeMultiSet - >; - - // BODY - export const Iterator = SetElementList.Iterator; - export const ReverseIterator = SetElementList.ReverseIterator; + // HEAD + /** + * Iterator of {@link TreeMultiSet} + */ + export type Iterator = SetElementList.Iterator< + Key, + false, + TreeMultiSet + >; + + /** + * Reverse iterator of {@link TreeMultiSet} + */ + export type ReverseIterator = SetElementList.ReverseIterator< + Key, + false, + TreeMultiSet + >; + + // BODY + export const Iterator = SetElementList.Iterator; + export const ReverseIterator = SetElementList.ReverseIterator; } diff --git a/src/container/TreeSet.ts b/src/container/TreeSet.ts index 8421bfe5..14c6aa94 100644 --- a/src/container/TreeSet.ts +++ b/src/container/TreeSet.ts @@ -1,18 +1,17 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { UniqueTreeSet } from "../internal/container/associative/UniqueTreeSet"; import { ITreeContainer } from "../internal/container/associative/ITreeContainer"; - -import { IForwardIterator } from "../iterator/IForwardIterator"; import { SetElementList } from "../internal/container/associative/SetElementList"; -import { UniqueSetTree } from "../internal/tree/UniqueSetTree"; - +import { UniqueTreeSet } from "../internal/container/associative/UniqueTreeSet"; import { Comparator } from "../internal/functional/Comparator"; import { Temporary } from "../internal/functional/Temporary"; +import { UniqueSetTree } from "../internal/tree/UniqueSetTree"; +import { IForwardIterator } from "../iterator/IForwardIterator"; /** * Unique-key Set based on Tree. @@ -20,164 +19,158 @@ import { Temporary } from "../internal/functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export class TreeSet extends UniqueTreeSet< - Key, - TreeSet, - TreeSet.Iterator, - TreeSet.ReverseIterator + Key, + TreeSet, + TreeSet.Iterator, + TreeSet.ReverseIterator > { - private tree_!: UniqueSetTree>; + private tree_!: UniqueSetTree>; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(comp?: Comparator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(items: Key[], comp?: Comparator); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(container: TreeSet); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor( - first: Readonly>, - last: Readonly>, - comp?: Comparator, + /** + * Default Constructor. + * + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(comp?: Comparator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(items: Key[], comp?: Comparator); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(container: TreeSet); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor( + first: Readonly>, + last: Readonly>, + comp?: Comparator, + ); + + public constructor(...args: any[]) { + super((thisArg) => new SetElementList(thisArg) as Temporary); + + ITreeContainer.construct< + Key, + Key, + TreeSet, + TreeSet.Iterator, + TreeSet.ReverseIterator, + Key + >( + this, + TreeSet, + (comp) => { + this.tree_ = new UniqueSetTree(this as TreeSet, comp); + }, + ...args, + ); + } + + /** + * @inheritDoc + */ + public clear(): void { + super.clear(); + + this.tree_.clear(); + } + + /** + * @inheritDoc + */ + public swap(obj: TreeSet): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + SetElementList._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, ); - public constructor(...args: any[]) { - super((thisArg) => new SetElementList(thisArg) as Temporary); - - ITreeContainer.construct< - Key, - Key, - TreeSet, - TreeSet.Iterator, - TreeSet.ReverseIterator, - Key - >( - this, - TreeSet, - (comp) => { - this.tree_ = new UniqueSetTree(this as TreeSet, comp); - }, - ...args, - ); - } - - /** - * @inheritDoc - */ - public clear(): void { - super.clear(); - - this.tree_.clear(); - } - - /** - * @inheritDoc - */ - public swap(obj: TreeSet): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - SetElementList._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP RB-TREE - UniqueSetTree._Swap_source(this.tree_, obj.tree_); - [this.tree_, obj.tree_] = [obj.tree_, this.tree_]; - } - - /* --------------------------------------------------------- + // SWAP RB-TREE + UniqueSetTree._Swap_source(this.tree_, obj.tree_); + [this.tree_, obj.tree_] = [obj.tree_, this.tree_]; + } + + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public key_comp(): Comparator { - return this.tree_.key_comp(); - } - - /** - * @inheritDoc - */ - public lower_bound(key: Key): TreeSet.Iterator { - return this.tree_.lower_bound(key); - } - - /** - * @inheritDoc - */ - public upper_bound(key: Key): TreeSet.Iterator { - return this.tree_.upper_bound(key); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public key_comp(): Comparator { + return this.tree_.key_comp(); + } + + /** + * @inheritDoc + */ + public lower_bound(key: Key): TreeSet.Iterator { + return this.tree_.lower_bound(key); + } + + /** + * @inheritDoc + */ + public upper_bound(key: Key): TreeSet.Iterator { + return this.tree_.upper_bound(key); + } + + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert( - first: TreeSet.Iterator, - last: TreeSet.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.tree_.insert(first); - } - - protected _Handle_erase( - first: TreeSet.Iterator, - last: TreeSet.Iterator, - ): void { - for (; !first.equals(last); first = first.next()) - this.tree_.erase(first); - } + protected _Handle_insert( + first: TreeSet.Iterator, + last: TreeSet.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) this.tree_.insert(first); + } + + protected _Handle_erase( + first: TreeSet.Iterator, + last: TreeSet.Iterator, + ): void { + for (; !first.equals(last); first = first.next()) this.tree_.erase(first); + } } /** * */ export namespace TreeSet { - // HEAD - /** - * Iterator of {@link TreeSet} - */ - export type Iterator = SetElementList.Iterator< - Key, - true, - TreeSet - >; - - /** - * Reverse iterator of {@link TreeSet} - */ - export type ReverseIterator = SetElementList.ReverseIterator< - Key, - true, - TreeSet - >; - - // BODY - export const Iterator = SetElementList.Iterator; - export const ReverseIterator = SetElementList.ReverseIterator; + // HEAD + /** + * Iterator of {@link TreeSet} + */ + export type Iterator = SetElementList.Iterator>; + + /** + * Reverse iterator of {@link TreeSet} + */ + export type ReverseIterator = SetElementList.ReverseIterator< + Key, + true, + TreeSet + >; + + // BODY + export const Iterator = SetElementList.Iterator; + export const ReverseIterator = SetElementList.ReverseIterator; } diff --git a/src/container/Vector.ts b/src/container/Vector.ts index 920edb41..d6331b86 100644 --- a/src/container/Vector.ts +++ b/src/container/Vector.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -6,7 +7,6 @@ //================================================================ import { IArrayContainer } from "../base/container/IArrayContainer"; import { VectorContainer } from "../internal/container/linear/VectorContainer"; - import { ArrayIterator } from "../internal/iterator/ArrayIterator"; import { ArrayReverseIterator } from "../internal/iterator/ArrayReverseIterator"; import { IForwardIterator } from "../iterator/IForwardIterator"; @@ -17,130 +17,130 @@ import { IForwardIterator } from "../iterator/IForwardIterator"; * @author Jeongho Nam - https://github.com/samchon */ export class Vector - extends VectorContainer< - T, - Vector, - Vector, - Vector.Iterator, - Vector.ReverseIterator + extends VectorContainer< + T, + Vector, + Vector, + Vector.Iterator, + Vector.ReverseIterator + > + implements + IArrayContainer< + T, + Vector, + Vector.Iterator, + Vector.ReverseIterator > - implements - IArrayContainer< - T, - Vector, - Vector.Iterator, - Vector.ReverseIterator - > { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor(); + /** + * Default Constructor. + */ + public constructor(); - /** - * Initializer Constructor. - * - * @param items Items to assign. - */ - public constructor(items: Array); + /** + * Initializer Constructor. + * + * @param items Items to assign. + */ + public constructor(items: Array); - /** - * @internal - */ - public constructor(items: Array, move: true); + /** + * @internal + */ + public constructor(items: Array, move: true); - /** - * Copy Constructor - * - * @param obj Object to copy. - */ - public constructor(obj: Vector); + /** + * Copy Constructor + * + * @param obj Object to copy. + */ + public constructor(obj: Vector); - /** - * Fill Constructor. - * - * @param size Initial size. - * @param val Value to fill. - */ - public constructor(n: number, val: T); + /** + * Fill Constructor. + * + * @param size Initial size. + * @param val Value to fill. + */ + public constructor(n: number, val: T); - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iteartor of the last position. - */ - public constructor( - first: Readonly>, - last: Readonly>, - ); + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iteartor of the last position. + */ + public constructor( + first: Readonly>, + last: Readonly>, + ); - public constructor(...args: any[]) { - super(); + public constructor(...args: any[]) { + super(); - // CONSTRUCTORS BRANCH - if (args.length === 0) { - // DEFAULT CONSTRUCTOR - this.data_ = []; - } else if (args[0] instanceof Array) { - // INITIALIZER CONSTRUCTOR - const array: Array = args[0]; - this.data_ = args[1] === true ? array : array.slice(); - } else if (args.length === 1 && args[0] instanceof Vector) { - // COPY CONSTRUCTOR - const v: Vector = args[0]; - this.data_ = v.data_.slice(); - } else if (args.length === 2) { - // ASSIGN CONSTRUCTOR - this.data_ = []; - this.assign(args[0], args[1]); - } + // CONSTRUCTORS BRANCH + if (args.length === 0) { + // DEFAULT CONSTRUCTOR + this.data_ = []; + } else if (args[0] instanceof Array) { + // INITIALIZER CONSTRUCTOR + const array: Array = args[0]; + this.data_ = args[1] === true ? array : array.slice(); + } else if (args.length === 1 && args[0] instanceof Vector) { + // COPY CONSTRUCTOR + const v: Vector = args[0]; + this.data_ = v.data_.slice(); + } else if (args.length === 2) { + // ASSIGN CONSTRUCTOR + this.data_ = []; + this.assign(args[0], args[1]); } + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * Wrap an array into a vector. - * - * @param data Target array to be wrapped - * @return A vector wrapping the parametric array. - */ - public static wrap(data: Array): Vector { - return new Vector(data, true); - } + /** + * Wrap an array into a vector. + * + * @param data Target array to be wrapped + * @return A vector wrapping the parametric array. + */ + public static wrap(data: Array): Vector { + return new Vector(data, true); + } - /** - * @inheritDoc - */ - public nth(index: number): Vector.Iterator { - return new Vector.Iterator(this as Vector, index); - } + /** + * @inheritDoc + */ + public nth(index: number): Vector.Iterator { + return new Vector.Iterator(this as Vector, index); + } - protected source(): Vector { - return this; - } + protected source(): Vector { + return this; + } } /** * */ export namespace Vector { - // HEAD - /** - * Iterator of {@link Vector} - */ - export type Iterator = ArrayIterator>; + // HEAD + /** + * Iterator of {@link Vector} + */ + export type Iterator = ArrayIterator>; - /** - * Reverse iterator of {@link Vector} - */ - export type ReverseIterator = ArrayReverseIterator>; + /** + * Reverse iterator of {@link Vector} + */ + export type ReverseIterator = ArrayReverseIterator>; - // BODY - export const Iterator = ArrayIterator; - export const ReverseIterator = ArrayReverseIterator; + // BODY + export const Iterator = ArrayIterator; + export const ReverseIterator = ArrayReverseIterator; } diff --git a/src/container/VectorBoolean.ts b/src/container/VectorBoolean.ts index 4c1e4b31..b5f27fd5 100644 --- a/src/container/VectorBoolean.ts +++ b/src/container/VectorBoolean.ts @@ -1,20 +1,19 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ import { IArrayContainer } from "../base/container/IArrayContainer"; +import { not_equal_to } from "../functional/comparators"; import { ArrayContainer } from "../internal/container/linear/ArrayContainer"; import { ArrayIterator } from "../internal/iterator/ArrayIterator"; import { ArrayReverseIterator } from "../internal/iterator/ArrayReverseIterator"; - -import { TreeMap } from "./TreeMap"; - -import { IForwardIterator } from "../iterator/IForwardIterator"; import { NativeArrayIterator } from "../internal/iterator/disposable/NativeArrayIterator"; +import { IForwardIterator } from "../iterator/IForwardIterator"; import { Pair } from "../utility/Pair"; -import { not_equal_to } from "../functional/comparators"; +import { TreeMap } from "./TreeMap"; /** * Vector only for `boolean`. @@ -22,238 +21,236 @@ import { not_equal_to } from "../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export class VectorBoolean - extends ArrayContainer< - boolean, - VectorBoolean, - VectorBoolean, - VectorBoolean.Iterator, - VectorBoolean.ReverseIterator, - boolean + extends ArrayContainer< + boolean, + VectorBoolean, + VectorBoolean, + VectorBoolean.Iterator, + VectorBoolean.ReverseIterator, + boolean + > + implements + IArrayContainer< + boolean, + VectorBoolean, + VectorBoolean.Iterator, + VectorBoolean.ReverseIterator > - implements - IArrayContainer< - boolean, - VectorBoolean, - VectorBoolean.Iterator, - VectorBoolean.ReverseIterator - > { - /** - * Store not full elements, but their sequence. - * - * - first: index - * - second: value - */ - private data_!: TreeMap; - - /** - * Number of elements - */ - private size_!: number; - - /* ========================================================= + /** + * Store not full elements, but their sequence. + * + * - first: index + * - second: value + */ + private data_!: TreeMap; + + /** + * Number of elements + */ + private size_!: number; + + /* ========================================================= CONSTRUCTORS & SEMI-CONSTRUCTORS - CONSTRUCTORS - ASSIGN & CLEAR ============================================================ CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor(); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - */ - public constructor(array: boolean[]); - - /** - * Copy Constructor - * - * @param obj Object to copy. - */ - public constructor(obj: VectorBoolean); - - /** - * Fill Constructor. - * - * @param size Initial size. - * @param val Value to fill. - */ - public constructor(n: number, val: boolean); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iteartor of the last position. - */ - public constructor( - first: Readonly>, - last: Readonly>, - ); - - public constructor(...args: any[]) { - super(); - - if (args.length === 1 && args[0] instanceof VectorBoolean) { - // COPY CONSTRUCTOR - const obj: VectorBoolean = args[0]; - - this.data_ = new TreeMap(obj.data_.begin(), obj.data_.end()); - this.size_ = obj.size_; - } else if (args.length === 1 && args[0] instanceof Array) { - // INITIALIZER - this.clear(); - this.push(...args[0]); - } else if (args.length === 2) { - // ASSIGNER - this.assign(args[0], args[1]); - } // DEFAULT CONSTRUCTOR - else this.clear(); - } - - /* --------------------------------------------------------- + /** + * Default Constructor. + */ + public constructor(); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + */ + public constructor(array: boolean[]); + + /** + * Copy Constructor + * + * @param obj Object to copy. + */ + public constructor(obj: VectorBoolean); + + /** + * Fill Constructor. + * + * @param size Initial size. + * @param val Value to fill. + */ + public constructor(n: number, val: boolean); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iteartor of the last position. + */ + public constructor( + first: Readonly>, + last: Readonly>, + ); + + public constructor(...args: any[]) { + super(); + + if (args.length === 1 && args[0] instanceof VectorBoolean) { + // COPY CONSTRUCTOR + const obj: VectorBoolean = args[0]; + + this.data_ = new TreeMap(obj.data_.begin(), obj.data_.end()); + this.size_ = obj.size_; + } else if (args.length === 1 && args[0] instanceof Array) { + // INITIALIZER + this.clear(); + this.push(...args[0]); + } else if (args.length === 2) { + // ASSIGNER + this.assign(args[0], args[1]); + } // DEFAULT CONSTRUCTOR + else this.clear(); + } + + /* --------------------------------------------------------- ASSIGN & CLEAR --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public assign(n: number, val: boolean): void; - /** - * @inheritDoc - */ - public assign< - InputIterator extends Readonly< - IForwardIterator - >, - >(first: InputIterator, last: InputIterator): void; - - public assign(first: any, last: any): void { - this.clear(); - this.insert(this.end(), first, last); - } - - /** - * @inheritDoc - */ - public clear(): void { - this.data_ = new TreeMap(); - this.size_ = 0; - } - - /** - * @inheritDoc - */ - public resize(n: number): void { - const expansion: number = n - this.size(); - if (expansion > 0) this.insert(this.end(), expansion, false); - else if (expansion < 0) - this.erase(this.end().advance(-expansion), this.end()); - } - - /** - * Flip all values. - */ - public flip(): void { - for (const entry of this.data_) entry.second = !entry.second; - } - - /** - * @inheritDoc - */ - public swap(obj: VectorBoolean): void { - [this.data_, obj.data_] = [obj.data_, this.data_]; - [this.size_, obj.size_] = [obj.size_, this.size_]; - } - - /* ========================================================= + /** + * @inheritDoc + */ + public assign(n: number, val: boolean): void; + /** + * @inheritDoc + */ + public assign< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void; + + public assign(first: any, last: any): void { + this.clear(); + this.insert(this.end(), first, last); + } + + /** + * @inheritDoc + */ + public clear(): void { + this.data_ = new TreeMap(); + this.size_ = 0; + } + + /** + * @inheritDoc + */ + public resize(n: number): void { + const expansion: number = n - this.size(); + if (expansion > 0) this.insert(this.end(), expansion, false); + else if (expansion < 0) + this.erase(this.end().advance(-expansion), this.end()); + } + + /** + * Flip all values. + */ + public flip(): void { + for (const entry of this.data_) entry.second = !entry.second; + } + + /** + * @inheritDoc + */ + public swap(obj: VectorBoolean): void { + [this.data_, obj.data_] = [obj.data_, this.data_]; + [this.size_, obj.size_] = [obj.size_, this.size_]; + } + + /* ========================================================= ACCESSORS ========================================================= */ - protected source(): VectorBoolean { - return this; - } - - /** - * @inheritDoc - */ - public size(): number { - return this.size_; - } - - protected _At(index: number): boolean { - // FIND THE NEAREST NODE OF LEFT - const it = this._Find_node(index); - return it.second; // RETURNS + protected source(): VectorBoolean { + return this; + } + + /** + * @inheritDoc + */ + public size(): number { + return this.size_; + } + + protected _At(index: number): boolean { + // FIND THE NEAREST NODE OF LEFT + const it = this._Find_node(index); + return it.second; // RETURNS + } + + protected _Set(index: number, val: boolean): void { + val = !!val; // SIFT + + // FIND THE NEAREAST NODE OF LEFT + let it = this._Find_node(index); + if (it.second === val) return; // NO NEED TO CHANGE + + //---- + // CHANGE VALUE + //---- + if (it.first === index) { + // CHANGE VALUE DIRECTLY + it.second = val; + } else { + // EMPLACE NEW NODE + it = this.data_.emplace(index, val).first; } - protected _Set(index: number, val: boolean): void { - val = !!val; // SIFT - - // FIND THE NEAREAST NODE OF LEFT - let it = this._Find_node(index); - if (it.second === val) return; // NO NEED TO CHANGE - - //---- - // CHANGE VALUE - //---- - if (it.first === index) { - // CHANGE VALUE DIRECTLY - it.second = val; - } else { - // EMPLACE NEW NODE - it = this.data_.emplace(index, val).first; - } - - //---- - // POST-PROCESS - //---- - // THE LAST ELEMENT, NO POST-PROCESS REQUIRED - if (index === this.size() - 1) return; - - // LIST UP NEIGHBORS - const prev = it.prev(); - const next = it.next(); - - // ARRANGE LEFT SIDE - if (not_equal_to(prev, this.data_.end()) && prev.second === it.second) - this.data_.erase(it); - - // ARRANGE RIGHT SIDE - if ( - next.equals(this.data_.end()) === true || - next.first !== index + 1 || - next.second !== val - ) { - // 1) IT'S THE LAST NODE - // 2) NEXT NODE DOES NOT POINT THE INDEX + 1 (NEAREST NEIGHBOR) - // 3) NEXT NODE'S VALUE IS DIFFERENT WITH THE CHANGED VALUE - //---- - // EMPLACE NEW NODE WITH OLD - this.data_.emplace(index + 1, !val); - } else { - // NEXT NODE'S VALUE IS SAME WITH THE CHANGED VALUE - //---- - // ERASE THE NEXT NODE - this.data_.erase(next); - } + //---- + // POST-PROCESS + //---- + // THE LAST ELEMENT, NO POST-PROCESS REQUIRED + if (index === this.size() - 1) return; + + // LIST UP NEIGHBORS + const prev = it.prev(); + const next = it.next(); + + // ARRANGE LEFT SIDE + if (not_equal_to(prev, this.data_.end()) && prev.second === it.second) + this.data_.erase(it); + + // ARRANGE RIGHT SIDE + if ( + next.equals(this.data_.end()) === true || + next.first !== index + 1 || + next.second !== val + ) { + // 1) IT'S THE LAST NODE + // 2) NEXT NODE DOES NOT POINT THE INDEX + 1 (NEAREST NEIGHBOR) + // 3) NEXT NODE'S VALUE IS DIFFERENT WITH THE CHANGED VALUE + //---- + // EMPLACE NEW NODE WITH OLD + this.data_.emplace(index + 1, !val); + } else { + // NEXT NODE'S VALUE IS SAME WITH THE CHANGED VALUE + //---- + // ERASE THE NEXT NODE + this.data_.erase(next); } + } - /** - * @inheritDoc - */ - public nth(index: number): VectorBoolean.Iterator { - return new VectorBoolean.Iterator(this as VectorBoolean, index); - } + /** + * @inheritDoc + */ + public nth(index: number): VectorBoolean.Iterator { + return new VectorBoolean.Iterator(this as VectorBoolean, index); + } - private _Find_node(index: number): TreeMap.Iterator { - return this.data_.upper_bound(index).prev(); - } + private _Find_node(index: number): TreeMap.Iterator { + return this.data_.upper_bound(index).prev(); + } - /* ========================================================= + /* ========================================================= ELEMENTS I/O - PUSH & POP - INSERT @@ -261,199 +258,193 @@ export class VectorBoolean ============================================================ PUSH & POP --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public push(...items: boolean[]): number { - if (items.length === 0) return this.size(); + /** + * @inheritDoc + */ + public push(...items: boolean[]): number { + if (items.length === 0) return this.size(); - const first = new NativeArrayIterator(items, 0); - const last = new NativeArrayIterator(items, items.length); + const first = new NativeArrayIterator(items, 0); + const last = new NativeArrayIterator(items, items.length); - this._Insert_by_range(this.end(), first, last); - return this.size(); - } + this._Insert_by_range(this.end(), first, last); + return this.size(); + } - /** - * @inheritDoc - */ - public push_back(val: boolean): void { - const it = this.data_.rbegin(); - const index: number = this.size_++; + /** + * @inheritDoc + */ + public push_back(val: boolean): void { + const it = this.data_.rbegin(); + const index: number = this.size_++; - val = !!val; // SIFT + val = !!val; // SIFT - // EMPLACE OR NOT - if (this.data_.empty() || it.second !== val) - this.data_.emplace(index, val); - } + // EMPLACE OR NOT + if (this.data_.empty() || it.second !== val) this.data_.emplace(index, val); + } - protected _Pop_back(): void { - const it: TreeMap.ReverseIterator = - this.data_.rbegin(); - const index: number = --this.size_; + protected _Pop_back(): void { + const it: TreeMap.ReverseIterator = this.data_.rbegin(); + const index: number = --this.size_; - // ERASE OR NOT - if (it.first === index) this.data_.erase(it.base()); - } + // ERASE OR NOT + if (it.first === index) this.data_.erase(it.base()); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - protected _Insert_by_repeating_val( - pos: VectorBoolean.Iterator, - n: number, - val: boolean, - ): VectorBoolean.Iterator { - // RESERVE ELEMENTS -> THE REPEATED COUNT AND VALUE - const elements: Pair[] = []; - elements.push(new Pair(n, val)); - - // DO INSERT - if (pos.equals(this.end()) === true) - return this._Insert_to_end(elements); - else return this._Insert_to_middle(pos, elements); + protected _Insert_by_repeating_val( + pos: VectorBoolean.Iterator, + n: number, + val: boolean, + ): VectorBoolean.Iterator { + // RESERVE ELEMENTS -> THE REPEATED COUNT AND VALUE + const elements: Pair[] = []; + elements.push(new Pair(n, val)); + + // DO INSERT + if (pos.equals(this.end()) === true) return this._Insert_to_end(elements); + else return this._Insert_to_middle(pos, elements); + } + + protected _Insert_by_range< + InputIterator extends Readonly>, + >( + pos: VectorBoolean.Iterator, + first: InputIterator, + last: InputIterator, + ): VectorBoolean.Iterator { + // RESERVE ELEMENTS -> REPEATED SIZE & VALUE + const elements: Pair[] = []; + + for (let it = first; !it.equals(last); it = it.next()) { + if ( + elements.length === 0 || + elements[elements.length - 1].second !== it.value + ) + elements.push(new Pair(1, it.value)); + else ++elements[elements.length - 1].first; } - protected _Insert_by_range< - InputIterator extends Readonly< - IForwardIterator - >, - >( - pos: VectorBoolean.Iterator, - first: InputIterator, - last: InputIterator, - ): VectorBoolean.Iterator { - // RESERVE ELEMENTS -> REPEATED SIZE & VALUE - const elements: Pair[] = []; - - for (let it = first; !it.equals(last); it = it.next()) { - if ( - elements.length === 0 || - elements[elements.length - 1].second !== it.value - ) - elements.push(new Pair(1, it.value)); - else ++elements[elements.length - 1].first; - } - - if (pos.equals(this.end()) === true) - return this._Insert_to_end(elements); - else return this._Insert_to_middle(pos, elements); + if (pos.equals(this.end()) === true) return this._Insert_to_end(elements); + else return this._Insert_to_middle(pos, elements); + } + + private _Insert_to_middle( + pos: VectorBoolean.Iterator, + elements: Pair[], + ): VectorBoolean.Iterator { + const first = this._Find_node(pos.index()); + + for (let it = first; !it.equals(this.data_.end()); it = it.next()) { + // COMPUTE SIZE TO ENROLL + const next: TreeMap.Iterator = it.next(); + + const sx: number = + it.first < pos.index() + ? pos.index() // POSITION TO INSERT + : it.first; // CURRENT POINT + const sy: number = next.equals(this.data_.end()) + ? this.size() // IT'S THE LAST ELEMENT + : next.first; // TO NEXT ELEMENT + + // DO ENROLL + const size: number = sy - sx; + const value: boolean = !!it.second; + + elements.push(new Pair(size, value)); } - private _Insert_to_middle( - pos: VectorBoolean.Iterator, - elements: Pair[], - ): VectorBoolean.Iterator { - const first = this._Find_node(pos.index()); - - for (let it = first; !it.equals(this.data_.end()); it = it.next()) { - // COMPUTE SIZE TO ENROLL - const next: TreeMap.Iterator = it.next(); - - const sx: number = - it.first < pos.index() - ? pos.index() // POSITION TO INSERT - : it.first; // CURRENT POINT - const sy: number = next.equals(this.data_.end()) - ? this.size() // IT'S THE LAST ELEMENT - : next.first; // TO NEXT ELEMENT - - // DO ENROLL - const size: number = sy - sx; - const value: boolean = !!it.second; - - elements.push(new Pair(size, value)); - } - - // ERASE BACK-SIDE ELEMENTS FOR THE POST-INSERTION - this.size_ = pos.index(); - this.data_.erase( - first.first === pos.index() ? first : first.next(), - this.data_.end(), - ); - - // DO POST-INSERTION - return this._Insert_to_end(elements); - } + // ERASE BACK-SIDE ELEMENTS FOR THE POST-INSERTION + this.size_ = pos.index(); + this.data_.erase( + first.first === pos.index() ? first : first.next(), + this.data_.end(), + ); - private _Insert_to_end( - elements: Pair[], - ): VectorBoolean.Iterator { - const old_size: number = this.size(); - const last_value: boolean | null = this.data_.empty() - ? null - : this.data_.rbegin().second; + // DO POST-INSERTION + return this._Insert_to_end(elements); + } - for (let i: number = 0; i < elements.length; ++i) { - const p: Pair = elements[i]; + private _Insert_to_end( + elements: Pair[], + ): VectorBoolean.Iterator { + const old_size: number = this.size(); + const last_value: boolean | null = this.data_.empty() + ? null + : this.data_.rbegin().second; - // INDEXING - const index: number = this.size(); - const value: boolean = !!p.second; + for (let i: number = 0; i < elements.length; ++i) { + const p: Pair = elements[i]; - this.size_ += p.first; + // INDEXING + const index: number = this.size(); + const value: boolean = !!p.second; - // NEED NOT TO EMPLACE, JUST SKIP - if (i === 0 && value === last_value) continue; + this.size_ += p.first; - // DO EMPLACE - this.data_.emplace(index, value); - } - return this.begin().advance(old_size); + // NEED NOT TO EMPLACE, JUST SKIP + if (i === 0 && value === last_value) continue; + + // DO EMPLACE + this.data_.emplace(index, value); } + return this.begin().advance(old_size); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - protected _Erase_by_range( - first: VectorBoolean.Iterator, - last: VectorBoolean.Iterator, - ): VectorBoolean.Iterator { - const elements: Pair[] = []; - - if (last.equals(this.end()) === false) { - const last_index: number = Math.min(this.size(), last.index()); - - for ( - let it = this._Find_node(last_index); - !it.equals(this.data_.end()); - it = it.next() - ) { - const next: TreeMap.Iterator = it.next(); - const sx: number = Math.max(it.first, last_index); - const sy: number = next.equals(this.data_.end()) - ? this.size() // IT'S THE LAST ELEMENT - : next.first; // TO NEXT ELEMENT - const size: number = sy - sx; - const value: boolean = it.second; - - elements.push(new Pair(size, value)); - } - } - - this.size_ = first.index(); - this.data_.erase(this.data_.lower_bound(this.size_), this.data_.end()); - return this._Insert_to_end(elements); + protected _Erase_by_range( + first: VectorBoolean.Iterator, + last: VectorBoolean.Iterator, + ): VectorBoolean.Iterator { + const elements: Pair[] = []; + + if (last.equals(this.end()) === false) { + const last_index: number = Math.min(this.size(), last.index()); + + for ( + let it = this._Find_node(last_index); + !it.equals(this.data_.end()); + it = it.next() + ) { + const next: TreeMap.Iterator = it.next(); + const sx: number = Math.max(it.first, last_index); + const sy: number = next.equals(this.data_.end()) + ? this.size() // IT'S THE LAST ELEMENT + : next.first; // TO NEXT ELEMENT + const size: number = sy - sx; + const value: boolean = it.second; + + elements.push(new Pair(size, value)); + } } + + this.size_ = first.index(); + this.data_.erase(this.data_.lower_bound(this.size_), this.data_.end()); + return this._Insert_to_end(elements); + } } /** * */ export namespace VectorBoolean { - // HEAD - /** - * Iterator of {@link VectorBoolean} - */ - export type Iterator = ArrayIterator; - - /** - * Reverse iterator of {@link VectorBoolean} - */ - export type ReverseIterator = ArrayReverseIterator; - - // BODY - export const Iterator = ArrayIterator; - export const ReverseIterator = ArrayReverseIterator; + // HEAD + /** + * Iterator of {@link VectorBoolean} + */ + export type Iterator = ArrayIterator; + + /** + * Reverse iterator of {@link VectorBoolean} + */ + export type ReverseIterator = ArrayReverseIterator; + + // BODY + export const Iterator = ArrayIterator; + export const ReverseIterator = ArrayReverseIterator; } diff --git a/src/exception/DomainError.ts b/src/exception/DomainError.ts index 4f427a35..d64091c9 100644 --- a/src/exception/DomainError.ts +++ b/src/exception/DomainError.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,12 +13,12 @@ import { LogicError } from "./LogicError"; * @author Jeongho Nam - https://github.com/samchon */ export class DomainError extends LogicError { - /** - * Initializer Constructor. - * - * @param message The error messgae. - */ - public constructor(message: string) { - super(message); - } + /** + * Initializer Constructor. + * + * @param message The error messgae. + */ + public constructor(message: string) { + super(message); + } } diff --git a/src/exception/ErrorCategory.ts b/src/exception/ErrorCategory.ts index 5871339b..736ceb6a 100644 --- a/src/exception/ErrorCategory.ts +++ b/src/exception/ErrorCategory.ts @@ -1,12 +1,13 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ +import { equal_to } from "../functional/comparators"; import { ErrorCode } from "./ErrorCode"; import { ErrorCondition } from "./ErrorCondition"; -import { equal_to } from "../functional/comparators"; /** * Error category. @@ -14,72 +15,72 @@ import { equal_to } from "../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class ErrorCategory { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor() {} + /** + * Default Constructor. + */ + public constructor() {} - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * Get category name. - */ - public abstract name(): string; + /** + * Get category name. + */ + public abstract name(): string; - /** - * Get error message. - * - * @param val Identifier of an error condition. - * @return The error message. - */ - public abstract message(val: number): string; + /** + * Get error message. + * + * @param val Identifier of an error condition. + * @return The error message. + */ + public abstract message(val: number): string; - /* --------------------------------------------------------- + /* --------------------------------------------------------- OPERATORS --------------------------------------------------------- */ - /** - * Get default error condition. - * - * @param val Identifier of an error condition. - * @return The error condition. - */ - public default_error_condition(val: number): ErrorCondition { - return new ErrorCondition(val, this); - } + /** + * Get default error condition. + * + * @param val Identifier of an error condition. + * @return The error condition. + */ + public default_error_condition(val: number): ErrorCondition { + return new ErrorCondition(val, this); + } - /** - * Test equivalence. - * - * @param val_code Identifier of an error code. - * @param cond An error condition. - * @return Whether equivalent or not. - */ - public equivalent(val_code: number, cond: ErrorCondition): boolean; + /** + * Test equivalence. + * + * @param val_code Identifier of an error code. + * @param cond An error condition. + * @return Whether equivalent or not. + */ + public equivalent(val_code: number, cond: ErrorCondition): boolean; - /** - * Test equivalence. - * - * @param code An error code. - * @param val_cond Identifier of an error condition. - * @return Whether equivalent or not. - */ - public equivalent(code: ErrorCode, val_cond: number): boolean; + /** + * Test equivalence. + * + * @param code An error code. + * @param val_cond Identifier of an error condition. + * @return Whether equivalent or not. + */ + public equivalent(code: ErrorCode, val_cond: number): boolean; - public equivalent(...args: any[]): boolean { - if (args[1] instanceof ErrorCondition) { - const val_code: number = args[0]; - const cond: ErrorCondition = args[1]; + public equivalent(...args: any[]): boolean { + if (args[1] instanceof ErrorCondition) { + const val_code: number = args[0]; + const cond: ErrorCondition = args[1]; - return equal_to(this.default_error_condition(val_code), cond); - } else { - const code: ErrorCode = args[0]; - const valcond: number = args[1]; + return equal_to(this.default_error_condition(val_code), cond); + } else { + const code: ErrorCode = args[0]; + const valcond: number = args[1]; - return equal_to(this, code.category()) && code.value() === valcond; - } + return equal_to(this, code.category()) && code.value() === valcond; } + } } diff --git a/src/exception/ErrorCode.ts b/src/exception/ErrorCode.ts index a814c67c..ee76121e 100644 --- a/src/exception/ErrorCode.ts +++ b/src/exception/ErrorCode.ts @@ -1,11 +1,11 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ import { ErrorInstance } from "../internal/exception/ErrorInstance"; - import { ErrorCategory } from "./ErrorCategory"; import { ErrorCondition } from "./ErrorCondition"; @@ -15,29 +15,29 @@ import { ErrorCondition } from "./ErrorCondition"; * @author Jeongho Nam - https://github.com/samchon */ export class ErrorCode extends ErrorInstance { - /** - * Default Constructor. - */ - public constructor(); + /** + * Default Constructor. + */ + public constructor(); - /** - * Initializer Constructor. - * - * @param val Identifier of an error instance. - * @param category An error category instance. - */ - public constructor(val: number, category: ErrorCategory); + /** + * Initializer Constructor. + * + * @param val Identifier of an error instance. + * @param category An error category instance. + */ + public constructor(val: number, category: ErrorCategory); - public constructor(val: number = 0, category: ErrorCategory | null = null) { - super(val, category!); - } + public constructor(val: number = 0, category: ErrorCategory | null = null) { + super(val, category!); + } - /** - * Get default error condition. - * - * @return The default error condition object. - */ - public default_error_condition(): ErrorCondition { - return this.category_.default_error_condition(this.value_); - } + /** + * Get default error condition. + * + * @return The default error condition object. + */ + public default_error_condition(): ErrorCondition { + return this.category_.default_error_condition(this.value_); + } } diff --git a/src/exception/ErrorCondition.ts b/src/exception/ErrorCondition.ts index 2e72c889..a9989cda 100644 --- a/src/exception/ErrorCondition.ts +++ b/src/exception/ErrorCondition.ts @@ -1,11 +1,11 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ import { ErrorInstance } from "../internal/exception/ErrorInstance"; - import { ErrorCategory } from "./ErrorCategory"; /** @@ -14,20 +14,20 @@ import { ErrorCategory } from "./ErrorCategory"; * @author Jeongho Nam - https://github.com/samchon */ export class ErrorCondition extends ErrorInstance { - /** - * Default Constructor. - */ - public constructor(); + /** + * Default Constructor. + */ + public constructor(); - /** - * Initializer Constructor. - * - * @param val Identifier of an error condition. - * @param category An error category instance. - */ - public constructor(val: number, category: ErrorCategory); + /** + * Initializer Constructor. + * + * @param val Identifier of an error condition. + * @param category An error category instance. + */ + public constructor(val: number, category: ErrorCategory); - public constructor(val: number = 0, category: ErrorCategory | null = null) { - super(val, category!); - } + public constructor(val: number = 0, category: ErrorCategory | null = null) { + super(val, category!); + } } diff --git a/src/exception/Exception.ts b/src/exception/Exception.ts index 7289d340..808e8ab0 100644 --- a/src/exception/Exception.ts +++ b/src/exception/Exception.ts @@ -10,54 +10,54 @@ * @author Jeongho Nam - https://github.com/samchon */ export class Exception extends Error { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * @param message The error messgae. - */ - public constructor(message: string) { - super(message); + /** + * Initializer Constructor. + * + * @param message The error messgae. + */ + public constructor(message: string) { + super(message); - // INHERITANCE POLYFILL - const proto = new.target.prototype; - if (Object.setPrototypeOf) Object.setPrototypeOf(this, proto); - else (this as any).__proto__ = proto; - } + // INHERITANCE POLYFILL + const proto = new.target.prototype; + if (Object.setPrototypeOf) Object.setPrototypeOf(this, proto); + else (this as any).__proto__ = proto; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * The error name. - */ - public get name(): string { - return this.constructor.name; - } + /** + * The error name. + */ + public get name(): string { + return this.constructor.name; + } - /** - * Get error message. - * - * @return The error message. - */ - public what(): string { - return this.message; - } + /** + * Get error message. + * + * @return The error message. + */ + public what(): string { + return this.message; + } - /** - * Native function for `JSON.stringify()`. - * - * The {@link Exception.toJSON} function returns only three properties; ({@link name}, {@link message} and {@link stack}). If you want to define a new sub-class extending the {@link Exception} and const the class to export additional props (or remove some props), override this {@link Exception.toJSON} method. - * - * @return An object for `JSON.stringify()`. - */ - public toJSON(): object { - return { - name: this.name, - message: this.message, - stack: this.stack, - }; - } + /** + * Native function for `JSON.stringify()`. + * + * The {@link Exception.toJSON} function returns only three properties; ({@link name}, {@link message} and {@link stack}). If you want to define a new sub-class extending the {@link Exception} and const the class to export additional props (or remove some props), override this {@link Exception.toJSON} method. + * + * @return An object for `JSON.stringify()`. + */ + public toJSON(): object { + return { + name: this.name, + message: this.message, + stack: this.stack, + }; + } } diff --git a/src/exception/InvalidArgument.ts b/src/exception/InvalidArgument.ts index 45cd7e35..71189381 100644 --- a/src/exception/InvalidArgument.ts +++ b/src/exception/InvalidArgument.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,12 +13,12 @@ import { LogicError } from "./LogicError"; * @author Jeongho Nam - https://github.com/samchon */ export class InvalidArgument extends LogicError { - /** - * Initializer Constructor. - * - * @param message The error messgae. - */ - public constructor(message: string) { - super(message); - } + /** + * Initializer Constructor. + * + * @param message The error messgae. + */ + public constructor(message: string) { + super(message); + } } diff --git a/src/exception/LengthError.ts b/src/exception/LengthError.ts index 5b03cded..adbeea68 100644 --- a/src/exception/LengthError.ts +++ b/src/exception/LengthError.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,12 +13,12 @@ import { LogicError } from "./LogicError"; * @author Jeongho Nam - https://github.com/samchon */ export class LengthError extends LogicError { - /** - * Initializer Constructor. - * - * @param message The error messgae. - */ - public constructor(message: string) { - super(message); - } + /** + * Initializer Constructor. + * + * @param message The error messgae. + */ + public constructor(message: string) { + super(message); + } } diff --git a/src/exception/LogicError.ts b/src/exception/LogicError.ts index f07311d1..402dc62b 100644 --- a/src/exception/LogicError.ts +++ b/src/exception/LogicError.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,12 +13,12 @@ import { Exception } from "./Exception"; * @author Jeongho Nam - https://github.com/samchon */ export class LogicError extends Exception { - /** - * Initializer Constructor. - * - * @param message The error messgae. - */ - public constructor(message: string) { - super(message); - } + /** + * Initializer Constructor. + * + * @param message The error messgae. + */ + public constructor(message: string) { + super(message); + } } diff --git a/src/exception/OutOfRange.ts b/src/exception/OutOfRange.ts index eafa41a8..c04c2441 100644 --- a/src/exception/OutOfRange.ts +++ b/src/exception/OutOfRange.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,12 +13,12 @@ import { LogicError } from "./LogicError"; * @author Jeongho Nam - https://github.com/samchon */ export class OutOfRange extends LogicError { - /** - * Initializer Constructor. - * - * @param message The error messgae. - */ - public constructor(message: string) { - super(message); - } + /** + * Initializer Constructor. + * + * @param message The error messgae. + */ + public constructor(message: string) { + super(message); + } } diff --git a/src/exception/OverflowError.ts b/src/exception/OverflowError.ts index 85a446c2..bb9dc3a8 100644 --- a/src/exception/OverflowError.ts +++ b/src/exception/OverflowError.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,12 +13,12 @@ import { RuntimeError } from "./RuntimeError"; * @author Jeongho Nam - https://github.com/samchon */ export class OverflowError extends RuntimeError { - /** - * Initializer Constructor. - * - * @param message The error messgae. - */ - public constructor(message: string) { - super(message); - } + /** + * Initializer Constructor. + * + * @param message The error messgae. + */ + public constructor(message: string) { + super(message); + } } diff --git a/src/exception/RangeError.ts b/src/exception/RangeError.ts index f1a7876d..634c4bd6 100644 --- a/src/exception/RangeError.ts +++ b/src/exception/RangeError.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,12 +13,12 @@ import { RuntimeError } from "./RuntimeError"; * @author Jeongho Nam - https://github.com/samchon */ export class RangeError extends RuntimeError { - /** - * Initializer Constructor. - * - * @param message The error messgae. - */ - public constructor(message: string) { - super(message); - } + /** + * Initializer Constructor. + * + * @param message The error messgae. + */ + public constructor(message: string) { + super(message); + } } diff --git a/src/exception/RuntimeError.ts b/src/exception/RuntimeError.ts index 3fd5db8a..cfa710d2 100644 --- a/src/exception/RuntimeError.ts +++ b/src/exception/RuntimeError.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,12 +13,12 @@ import { Exception } from "./Exception"; * @author Jeongho Nam - https://github.com/samchon */ export class RuntimeError extends Exception { - /** - * Initializer Constructor. - * - * @param message The error messgae. - */ - public constructor(message: string) { - super(message); - } + /** + * Initializer Constructor. + * + * @param message The error messgae. + */ + public constructor(message: string) { + super(message); + } } diff --git a/src/exception/SystemError.ts b/src/exception/SystemError.ts index 0186bb61..8f0efc5f 100644 --- a/src/exception/SystemError.ts +++ b/src/exception/SystemError.ts @@ -1,13 +1,13 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { RuntimeError } from "./RuntimeError"; - -import { ErrorCode } from "./ErrorCode"; import { ErrorCategory } from "./ErrorCategory"; +import { ErrorCode } from "./ErrorCode"; +import { RuntimeError } from "./RuntimeError"; /** * System Error. @@ -15,62 +15,62 @@ import { ErrorCategory } from "./ErrorCategory"; * @author Jeongho Nam - https://github.com/samchon */ export class SystemError extends RuntimeError { - protected code_: ErrorCode; + protected code_: ErrorCode; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * @param code An error code. - * @param message A detailed error message. - */ - public constructor(code: ErrorCode, message?: string); + /** + * Initializer Constructor. + * + * @param code An error code. + * @param message A detailed error message. + */ + public constructor(code: ErrorCode, message?: string); - /** - * Construct from references. - * - * @param val Identnfier of an error code in *category*. - * @param category An error category. - * @param message A detailed error message. - */ - public constructor(val: number, category: ErrorCategory, message?: string); + /** + * Construct from references. + * + * @param val Identnfier of an error code in *category*. + * @param category An error category. + * @param message A detailed error message. + */ + public constructor(val: number, category: ErrorCategory, message?: string); - public constructor(...args: any[]) { - super(""); + public constructor(...args: any[]) { + super(""); - if (args.length >= 2 && typeof args[0].valueOf() === "number") { - const val: number = args[0]; - const category: ErrorCategory = args[1]; + if (args.length >= 2 && typeof args[0].valueOf() === "number") { + const val: number = args[0]; + const category: ErrorCategory = args[1]; - this.code_ = new ErrorCode(val, category); - this.message = args[2]; - } else { - this.code_ = args[0]; - this.message = args[1]; - } + this.code_ = new ErrorCode(val, category); + this.message = args[2]; + } else { + this.code_ = args[0]; + this.message = args[1]; } + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * Get error code. - * - * @return The error code. - */ - public code(): ErrorCode { - return this.code_; - } + /** + * Get error code. + * + * @return The error code. + */ + public code(): ErrorCode { + return this.code_; + } - /** - * @inheritDoc - */ - public toJSON(): object { - return { - ...super.toJSON(), - code: this.code_.toJSON(), - }; - } + /** + * @inheritDoc + */ + public toJSON(): object { + return { + ...super.toJSON(), + code: this.code_.toJSON(), + }; + } } diff --git a/src/exception/UnderflowError.ts b/src/exception/UnderflowError.ts index 06c2b37f..01f774c8 100644 --- a/src/exception/UnderflowError.ts +++ b/src/exception/UnderflowError.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,12 +13,12 @@ import { RuntimeError } from "./RuntimeError"; * @author Jeongho Nam - https://github.com/samchon */ export class UnderflowError extends RuntimeError { - /** - * Initializer Constructor. - * - * @param message The error messgae. - */ - public constructor(message: string) { - super(message); - } + /** + * Initializer Constructor. + * + * @param message The error messgae. + */ + public constructor(message: string) { + super(message); + } } diff --git a/src/experimental/container/FlatMap.ts b/src/experimental/container/FlatMap.ts index cc5e6cb2..63b6adcc 100644 --- a/src/experimental/container/FlatMap.ts +++ b/src/experimental/container/FlatMap.ts @@ -1,20 +1,19 @@ //================================================================ + /** * @packageDocumentation * @module std.experimental */ //================================================================ -import { UniqueTreeMap } from "../../internal/container/associative/UniqueTreeMap"; +import { lower_bound, upper_bound } from "../../algorithm/binary_search"; import { ITreeContainer } from "../../internal/container/associative/ITreeContainer"; - import { MapElementVector } from "../../internal/container/associative/MapElementVector"; -import { IPair } from "../../utility/IPair"; -import { Entry } from "../../utility/Entry"; - -import { IForwardIterator } from "../../iterator/IForwardIterator"; +import { UniqueTreeMap } from "../../internal/container/associative/UniqueTreeMap"; import { Comparator } from "../../internal/functional/Comparator"; import { Temporary } from "../../internal/functional/Temporary"; -import { lower_bound, upper_bound } from "../../algorithm/binary_search"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; +import { Entry } from "../../utility/Entry"; +import { IPair } from "../../utility/IPair"; /** * Unique-key Map based on sorted array. @@ -22,165 +21,165 @@ import { lower_bound, upper_bound } from "../../algorithm/binary_search"; * @author Jeongho Nam - https://github.com/samchon */ export class FlatMap extends UniqueTreeMap< - Key, - T, - FlatMap, - FlatMap.Iterator, - FlatMap.ReverseIterator + Key, + T, + FlatMap, + FlatMap.Iterator, + FlatMap.ReverseIterator > { - private key_comp_!: Comparator; + private key_comp_!: Comparator; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(comp?: Comparator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(items: IPair[], comp?: Comparator); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: FlatMap); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor( - first: Readonly>>, - last: Readonly>>, - comp?: Comparator, + /** + * Default Constructor. + * + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(comp?: Comparator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(items: IPair[], comp?: Comparator); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: FlatMap); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor( + first: Readonly>>, + last: Readonly>>, + comp?: Comparator, + ); + + public constructor(...args: any[]) { + // INITIALIZATION + super((thisArg) => new MapElementVector(thisArg)); + + // OVERLOADINGS + ITreeContainer.construct< + Key, + Entry, + FlatMap, + FlatMap.Iterator, + FlatMap.ReverseIterator, + IPair + >( + this, + FlatMap, + (comp) => { + this.key_comp_ = comp; + }, + ...args, + ); + } + + /** + * @inheritDoc + */ + public swap(obj: FlatMap): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + MapElementVector._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, ); - public constructor(...args: any[]) { - // INITIALIZATION - super((thisArg) => new MapElementVector(thisArg)); - - // OVERLOADINGS - ITreeContainer.construct< - Key, - Entry, - FlatMap, - FlatMap.Iterator, - FlatMap.ReverseIterator, - IPair - >( - this, - FlatMap, - (comp) => { - this.key_comp_ = comp; - }, - ...args, - ); - } - - /** - * @inheritDoc - */ - public swap(obj: FlatMap): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - MapElementVector._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP COMPARATORS - [this.key_comp_, obj.key_comp_] = [obj.key_comp_, this.key_comp_]; - } - - /* --------------------------------------------------------- + // SWAP COMPARATORS + [this.key_comp_, obj.key_comp_] = [obj.key_comp_, this.key_comp_]; + } + + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public nth(index: number): FlatMap.Iterator { - return ( - this.data_ as MapElementVector> - ).nth(index); - } - - /** - * @inheritDoc - */ - public key_comp(): Comparator { - return this.key_comp_; - } - - /** - * @inheritDoc - */ - public lower_bound(key: Key): FlatMap.Iterator { - return lower_bound( - this.begin(), - this.end(), - this._Capsule_key(key), - this.value_comp(), - ); - } - - /** - * @inheritDoc - */ - public upper_bound(key: Key): FlatMap.Iterator { - return upper_bound( - this.begin(), - this.end(), - this._Capsule_key(key), - this.value_comp(), - ); - } - - private _Capsule_key(key: Key): Entry { - return { first: key } as Entry; - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public nth(index: number): FlatMap.Iterator { + return (this.data_ as MapElementVector>).nth( + index, + ); + } + + /** + * @inheritDoc + */ + public key_comp(): Comparator { + return this.key_comp_; + } + + /** + * @inheritDoc + */ + public lower_bound(key: Key): FlatMap.Iterator { + return lower_bound( + this.begin(), + this.end(), + this._Capsule_key(key), + this.value_comp(), + ); + } + + /** + * @inheritDoc + */ + public upper_bound(key: Key): FlatMap.Iterator { + return upper_bound( + this.begin(), + this.end(), + this._Capsule_key(key), + this.value_comp(), + ); + } + + private _Capsule_key(key: Key): Entry { + return { first: key } as Entry; + } + + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert({}, {}): void {} + protected _Handle_insert({}, {}): void {} - protected _Handle_erase({}, {}): void {} + protected _Handle_erase({}, {}): void {} } /** * */ export namespace FlatMap { - // HEAD - export type Iterator = MapElementVector.Iterator< - Key, - T, - true, - FlatMap - >; - export type ReverseIterator = MapElementVector.ReverseIterator< - Key, - T, - true, - FlatMap - >; - - // BODY - export const Iterator = MapElementVector.Iterator; - export const ReverseIterator = MapElementVector.ReverseIterator; - - export const __MODULE = "experimental"; + // HEAD + export type Iterator = MapElementVector.Iterator< + Key, + T, + true, + FlatMap + >; + export type ReverseIterator = MapElementVector.ReverseIterator< + Key, + T, + true, + FlatMap + >; + + // BODY + export const Iterator = MapElementVector.Iterator; + export const ReverseIterator = MapElementVector.ReverseIterator; + + export const __MODULE = "experimental"; } diff --git a/src/experimental/container/FlatMultiMap.ts b/src/experimental/container/FlatMultiMap.ts index b35fd3e3..08e98916 100644 --- a/src/experimental/container/FlatMultiMap.ts +++ b/src/experimental/container/FlatMultiMap.ts @@ -1,20 +1,19 @@ //================================================================ + /** * @packageDocumentation * @module std.experimental */ //================================================================ -import { MultiTreeMap } from "../../internal/container/associative/MultiTreeMap"; +import { lower_bound, upper_bound } from "../../algorithm/binary_search"; import { ITreeContainer } from "../../internal/container/associative/ITreeContainer"; - import { MapElementVector } from "../../internal/container/associative/MapElementVector"; -import { IPair } from "../../utility/IPair"; -import { Entry } from "../../utility/Entry"; - -import { IForwardIterator } from "../../iterator/IForwardIterator"; +import { MultiTreeMap } from "../../internal/container/associative/MultiTreeMap"; import { Comparator } from "../../internal/functional/Comparator"; import { Temporary } from "../../internal/functional/Temporary"; -import { lower_bound, upper_bound } from "../../algorithm/binary_search"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; +import { Entry } from "../../utility/Entry"; +import { IPair } from "../../utility/IPair"; /** * Multiple-key Map based on sorted array. @@ -22,165 +21,165 @@ import { lower_bound, upper_bound } from "../../algorithm/binary_search"; * @author Jeongho Nam - https://github.com/samchon */ export class FlatMultiMap extends MultiTreeMap< - Key, - T, - FlatMultiMap, - FlatMultiMap.Iterator, - FlatMultiMap.ReverseIterator + Key, + T, + FlatMultiMap, + FlatMultiMap.Iterator, + FlatMultiMap.ReverseIterator > { - private key_comp_!: Comparator; + private key_comp_!: Comparator; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(comp?: Comparator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(items: IPair[], comp?: Comparator); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: FlatMultiMap); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor( - first: Readonly>>, - last: Readonly>>, - comp?: Comparator, + /** + * Default Constructor. + * + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(comp?: Comparator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(items: IPair[], comp?: Comparator); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: FlatMultiMap); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor( + first: Readonly>>, + last: Readonly>>, + comp?: Comparator, + ); + + public constructor(...args: any[]) { + // INITIALIZATION + super((thisArg) => new MapElementVector(thisArg)); + + // OVERLOADINGS + ITreeContainer.construct< + Key, + Entry, + FlatMultiMap, + FlatMultiMap.Iterator, + FlatMultiMap.ReverseIterator, + IPair + >( + this, + FlatMultiMap, + (comp) => { + this.key_comp_ = comp; + }, + ...args, + ); + } + + /** + * @inheritDoc + */ + public swap(obj: FlatMultiMap): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + MapElementVector._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, ); - public constructor(...args: any[]) { - // INITIALIZATION - super((thisArg) => new MapElementVector(thisArg)); - - // OVERLOADINGS - ITreeContainer.construct< - Key, - Entry, - FlatMultiMap, - FlatMultiMap.Iterator, - FlatMultiMap.ReverseIterator, - IPair - >( - this, - FlatMultiMap, - (comp) => { - this.key_comp_ = comp; - }, - ...args, - ); - } - - /** - * @inheritDoc - */ - public swap(obj: FlatMultiMap): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - MapElementVector._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP COMPARATORS - [this.key_comp_, obj.key_comp_] = [obj.key_comp_, this.key_comp_]; - } - - /* --------------------------------------------------------- + // SWAP COMPARATORS + [this.key_comp_, obj.key_comp_] = [obj.key_comp_, this.key_comp_]; + } + + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public nth(index: number): FlatMultiMap.Iterator { - return ( - this.data_ as MapElementVector> - ).nth(index); - } - - /** - * @inheritDoc - */ - public key_comp(): Comparator { - return this.key_comp_; - } - - /** - * @inheritDoc - */ - public lower_bound(key: Key): FlatMultiMap.Iterator { - return lower_bound( - this.begin(), - this.end(), - this._Capsule_key(key), - this.value_comp(), - ); - } - - /** - * @inheritDoc - */ - public upper_bound(key: Key): FlatMultiMap.Iterator { - return upper_bound( - this.begin(), - this.end(), - this._Capsule_key(key), - this.value_comp(), - ); - } - - private _Capsule_key(key: Key): Entry { - return { first: key } as Entry; - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public nth(index: number): FlatMultiMap.Iterator { + return ( + this.data_ as MapElementVector> + ).nth(index); + } + + /** + * @inheritDoc + */ + public key_comp(): Comparator { + return this.key_comp_; + } + + /** + * @inheritDoc + */ + public lower_bound(key: Key): FlatMultiMap.Iterator { + return lower_bound( + this.begin(), + this.end(), + this._Capsule_key(key), + this.value_comp(), + ); + } + + /** + * @inheritDoc + */ + public upper_bound(key: Key): FlatMultiMap.Iterator { + return upper_bound( + this.begin(), + this.end(), + this._Capsule_key(key), + this.value_comp(), + ); + } + + private _Capsule_key(key: Key): Entry { + return { first: key } as Entry; + } + + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert({}, {}): void {} + protected _Handle_insert({}, {}): void {} - protected _Handle_erase({}, {}): void {} + protected _Handle_erase({}, {}): void {} } /** * */ export namespace FlatMultiMap { - // HEAD - export type Iterator = MapElementVector.Iterator< - Key, - T, - false, - FlatMultiMap - >; - export type ReverseIterator = MapElementVector.ReverseIterator< - Key, - T, - false, - FlatMultiMap - >; - - // BODY - export const Iterator = MapElementVector.Iterator; - export const ReverseIterator = MapElementVector.ReverseIterator; - - export const __MODULE = "experimental"; + // HEAD + export type Iterator = MapElementVector.Iterator< + Key, + T, + false, + FlatMultiMap + >; + export type ReverseIterator = MapElementVector.ReverseIterator< + Key, + T, + false, + FlatMultiMap + >; + + // BODY + export const Iterator = MapElementVector.Iterator; + export const ReverseIterator = MapElementVector.ReverseIterator; + + export const __MODULE = "experimental"; } diff --git a/src/experimental/container/FlatMultiSet.ts b/src/experimental/container/FlatMultiSet.ts index c7c0e6c5..f55ebf04 100644 --- a/src/experimental/container/FlatMultiSet.ts +++ b/src/experimental/container/FlatMultiSet.ts @@ -1,18 +1,17 @@ //================================================================ + /** * @packageDocumentation * @module std.experimental */ //================================================================ -import { MultiTreeSet } from "../../internal/container/associative/MultiTreeSet"; +import { lower_bound, upper_bound } from "../../algorithm/binary_search"; import { ITreeContainer } from "../../internal/container/associative/ITreeContainer"; - +import { MultiTreeSet } from "../../internal/container/associative/MultiTreeSet"; import { SetElementVector } from "../../internal/container/associative/SetElementVector"; - -import { IForwardIterator } from "../../iterator/IForwardIterator"; import { Comparator } from "../../internal/functional/Comparator"; import { Temporary } from "../../internal/functional/Temporary"; -import { lower_bound, upper_bound } from "../../algorithm/binary_search"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; /** * Multiple-key Set based on sorted array. @@ -20,148 +19,148 @@ import { lower_bound, upper_bound } from "../../algorithm/binary_search"; * @author Jeongho Nam - https://github.com/samchon */ export class FlatMultiSet extends MultiTreeSet< - Key, - FlatMultiSet, - FlatMultiSet.Iterator, - FlatMultiSet.ReverseIterator + Key, + FlatMultiSet, + FlatMultiSet.Iterator, + FlatMultiSet.ReverseIterator > { - private key_comp_!: Comparator; + private key_comp_!: Comparator; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(comp?: Comparator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(items: Key[], comp?: Comparator); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: FlatMultiSet); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor( - first: Readonly>, - last: Readonly>, - comp?: Comparator, + /** + * Default Constructor. + * + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(comp?: Comparator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(items: Key[], comp?: Comparator); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: FlatMultiSet); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor( + first: Readonly>, + last: Readonly>, + comp?: Comparator, + ); + + public constructor(...args: any[]) { + // INITIALIZATION + super((thisArg) => new SetElementVector(thisArg)); + + // OVERLOADINGS + ITreeContainer.construct< + Key, + Key, + FlatMultiSet, + FlatMultiSet.Iterator, + FlatMultiSet.ReverseIterator, + Key + >( + this, + FlatMultiSet, + (comp) => { + this.key_comp_ = comp; + }, + ...args, + ); + } + + /** + * @inheritDoc + */ + public swap(obj: FlatMultiSet): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + SetElementVector._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, ); - public constructor(...args: any[]) { - // INITIALIZATION - super((thisArg) => new SetElementVector(thisArg)); - - // OVERLOADINGS - ITreeContainer.construct< - Key, - Key, - FlatMultiSet, - FlatMultiSet.Iterator, - FlatMultiSet.ReverseIterator, - Key - >( - this, - FlatMultiSet, - (comp) => { - this.key_comp_ = comp; - }, - ...args, - ); - } - - /** - * @inheritDoc - */ - public swap(obj: FlatMultiSet): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - SetElementVector._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP COMPARATORS - [this.key_comp_, obj.key_comp_] = [obj.key_comp_, this.key_comp_]; - } - - /* --------------------------------------------------------- + // SWAP COMPARATORS + [this.key_comp_, obj.key_comp_] = [obj.key_comp_, this.key_comp_]; + } + + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public nth(index: number): FlatMultiSet.Iterator { - return ( - this.data_ as SetElementVector> - ).nth(index); - } - - /** - * @inheritDoc - */ - public key_comp(): Comparator { - return this.key_comp_; - } - - /** - * @inheritDoc - */ - public lower_bound(key: Key): FlatMultiSet.Iterator { - return lower_bound(this.begin(), this.end(), key, this.value_comp()); - } - - /** - * @inheritDoc - */ - public upper_bound(key: Key): FlatMultiSet.Iterator { - return upper_bound(this.begin(), this.end(), key, this.value_comp()); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public nth(index: number): FlatMultiSet.Iterator { + return (this.data_ as SetElementVector>).nth( + index, + ); + } + + /** + * @inheritDoc + */ + public key_comp(): Comparator { + return this.key_comp_; + } + + /** + * @inheritDoc + */ + public lower_bound(key: Key): FlatMultiSet.Iterator { + return lower_bound(this.begin(), this.end(), key, this.value_comp()); + } + + /** + * @inheritDoc + */ + public upper_bound(key: Key): FlatMultiSet.Iterator { + return upper_bound(this.begin(), this.end(), key, this.value_comp()); + } + + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert({}, {}): void {} + protected _Handle_insert({}, {}): void {} - protected _Handle_erase({}, {}): void {} + protected _Handle_erase({}, {}): void {} } /** * */ export namespace FlatMultiSet { - // HEAD - export type Iterator = SetElementVector.Iterator< - Key, - false, - FlatMultiSet - >; - export type ReverseIterator = SetElementVector.ReverseIterator< - Key, - false, - FlatMultiSet - >; - - // BODY - export const Iterator = SetElementVector.Iterator; - export const ReverseIterator = SetElementVector.ReverseIterator; - - export const __MODULE = "experimental"; + // HEAD + export type Iterator = SetElementVector.Iterator< + Key, + false, + FlatMultiSet + >; + export type ReverseIterator = SetElementVector.ReverseIterator< + Key, + false, + FlatMultiSet + >; + + // BODY + export const Iterator = SetElementVector.Iterator; + export const ReverseIterator = SetElementVector.ReverseIterator; + + export const __MODULE = "experimental"; } diff --git a/src/experimental/container/FlatSet.ts b/src/experimental/container/FlatSet.ts index 9c390617..504e9204 100644 --- a/src/experimental/container/FlatSet.ts +++ b/src/experimental/container/FlatSet.ts @@ -1,18 +1,17 @@ //================================================================ + /** * @packageDocumentation * @module std.experimental */ //================================================================ -import { UniqueTreeSet } from "../../internal/container/associative/UniqueTreeSet"; +import { lower_bound, upper_bound } from "../../algorithm/binary_search"; import { ITreeContainer } from "../../internal/container/associative/ITreeContainer"; - import { SetElementVector } from "../../internal/container/associative/SetElementVector"; - -import { IForwardIterator } from "../../iterator/IForwardIterator"; +import { UniqueTreeSet } from "../../internal/container/associative/UniqueTreeSet"; import { Comparator } from "../../internal/functional/Comparator"; import { Temporary } from "../../internal/functional/Temporary"; -import { lower_bound, upper_bound } from "../../algorithm/binary_search"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; /** * Unique-key Set based on sorted array. @@ -20,148 +19,146 @@ import { lower_bound, upper_bound } from "../../algorithm/binary_search"; * @author Jeongho Nam - https://github.com/samchon */ export class FlatSet extends UniqueTreeSet< - Key, - FlatSet, - FlatSet.Iterator, - FlatSet.ReverseIterator + Key, + FlatSet, + FlatSet.Iterator, + FlatSet.ReverseIterator > { - private key_comp_!: Comparator; + private key_comp_!: Comparator; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTURCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - * - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(comp?: Comparator); - - /** - * Initializer Constructor. - * - * @param items Items to assign. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor(items: Key[], comp?: Comparator); - - /** - * Copy Constructor. - * - * @param obj Object to copy. - */ - public constructor(obj: FlatSet); - - /** - * Range Constructor. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. - */ - public constructor( - first: Readonly>, - last: Readonly>, - comp?: Comparator, + /** + * Default Constructor. + * + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(comp?: Comparator); + + /** + * Initializer Constructor. + * + * @param items Items to assign. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor(items: Key[], comp?: Comparator); + + /** + * Copy Constructor. + * + * @param obj Object to copy. + */ + public constructor(obj: FlatSet); + + /** + * Range Constructor. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Note that, because *equality* is predicated by `!comp(x, y) && !comp(y, x)`, the function must not cover the *equality* like `<=` or `>=`. It must exclude the *equality* like `<` or `>`. Default is {@link less}. + */ + public constructor( + first: Readonly>, + last: Readonly>, + comp?: Comparator, + ); + + public constructor(...args: any[]) { + // INITIALIZATION + super((thisArg) => new SetElementVector(thisArg)); + + // OVERLOADINGS + ITreeContainer.construct< + Key, + Key, + FlatSet, + FlatSet.Iterator, + FlatSet.ReverseIterator, + Key + >( + this, + FlatSet, + (comp) => { + this.key_comp_ = comp; + }, + ...args, ); + } + + /** + * @inheritDoc + */ + public swap(obj: FlatSet): void { + // SWAP CONTENTS + [this.data_, obj.data_] = [obj.data_, this.data_]; + SetElementVector._Swap_associative( + this.data_ as Temporary, + obj.data_ as Temporary, + ); + + // SWAP COMPARATORS + [this.key_comp_, obj.key_comp_] = [obj.key_comp_, this.key_comp_]; + } - public constructor(...args: any[]) { - // INITIALIZATION - super((thisArg) => new SetElementVector(thisArg)); - - // OVERLOADINGS - ITreeContainer.construct< - Key, - Key, - FlatSet, - FlatSet.Iterator, - FlatSet.ReverseIterator, - Key - >( - this, - FlatSet, - (comp) => { - this.key_comp_ = comp; - }, - ...args, - ); - } - - /** - * @inheritDoc - */ - public swap(obj: FlatSet): void { - // SWAP CONTENTS - [this.data_, obj.data_] = [obj.data_, this.data_]; - SetElementVector._Swap_associative( - this.data_ as Temporary, - obj.data_ as Temporary, - ); - - // SWAP COMPARATORS - [this.key_comp_, obj.key_comp_] = [obj.key_comp_, this.key_comp_]; - } - - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public nth(index: number): FlatSet.Iterator { - return (this.data_ as SetElementVector>).nth( - index, - ); - } - - /** - * @inheritDoc - */ - public key_comp(): Comparator { - return this.key_comp_; - } - - /** - * @inheritDoc - */ - public lower_bound(key: Key): FlatSet.Iterator { - return lower_bound(this.begin(), this.end(), key, this.value_comp()); - } - - /** - * @inheritDoc - */ - public upper_bound(key: Key): FlatSet.Iterator { - return upper_bound(this.begin(), this.end(), key, this.value_comp()); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public nth(index: number): FlatSet.Iterator { + return (this.data_ as SetElementVector>).nth(index); + } + + /** + * @inheritDoc + */ + public key_comp(): Comparator { + return this.key_comp_; + } + + /** + * @inheritDoc + */ + public lower_bound(key: Key): FlatSet.Iterator { + return lower_bound(this.begin(), this.end(), key, this.value_comp()); + } + + /** + * @inheritDoc + */ + public upper_bound(key: Key): FlatSet.Iterator { + return upper_bound(this.begin(), this.end(), key, this.value_comp()); + } + + /* --------------------------------------------------------- POST-PROCESS --------------------------------------------------------- */ - protected _Handle_insert({}, {}): void {} + protected _Handle_insert({}, {}): void {} - protected _Handle_erase({}, {}): void {} + protected _Handle_erase({}, {}): void {} } /** * */ export namespace FlatSet { - // HEAD - export type Iterator = SetElementVector.Iterator< - Key, - true, - FlatSet - >; - export type ReverseIterator = SetElementVector.ReverseIterator< - Key, - true, - FlatSet - >; - - // BODY - export const Iterator = SetElementVector.Iterator; - export const ReverseIterator = SetElementVector.ReverseIterator; - - export const __MODULE = "experimental"; + // HEAD + export type Iterator = SetElementVector.Iterator< + Key, + true, + FlatSet + >; + export type ReverseIterator = SetElementVector.ReverseIterator< + Key, + true, + FlatSet + >; + + // BODY + export const Iterator = SetElementVector.Iterator; + export const ReverseIterator = SetElementVector.ReverseIterator; + + export const __MODULE = "experimental"; } diff --git a/src/experimental/index.ts b/src/experimental/index.ts index d3adb905..f2b4c3fc 100644 --- a/src/experimental/index.ts +++ b/src/experimental/index.ts @@ -1,4 +1,5 @@ //================================================================ + /** * Experimental Features * diff --git a/src/functional/IComparable.ts b/src/functional/IComparable.ts index b888afd0..858e00df 100644 --- a/src/functional/IComparable.ts +++ b/src/functional/IComparable.ts @@ -10,26 +10,26 @@ * @author Jeongho Nam - https://github.com/samchon */ export interface IComparable { - /** - * Test whether equal to some object. - * - * @param obj The object to compare. - * @return Whether equal or not. - */ - equals(obj: T): boolean; + /** + * Test whether equal to some object. + * + * @param obj The object to compare. + * @return Whether equal or not. + */ + equals(obj: T): boolean; - /** - * Test whether less than some object. - * - * @param obj The object to compare. - * @return Whether less or not. - */ - less(obj: T): boolean; + /** + * Test whether less than some object. + * + * @param obj The object to compare. + * @return Whether less or not. + */ + less(obj: T): boolean; - /** - * Get hash code. - * - * @return The hash code. - */ - hashCode(): number; + /** + * Get hash code. + * + * @return The hash code. + */ + hashCode(): number; } diff --git a/src/functional/IPointer.ts b/src/functional/IPointer.ts index 553b80cc..9aabd521 100644 --- a/src/functional/IPointer.ts +++ b/src/functional/IPointer.ts @@ -10,16 +10,16 @@ * @author Jeongho Nam - https://github.com/samchon */ export interface IPointer { - /** - * Reference of the value. - */ - value: T; + /** + * Reference of the value. + */ + value: T; } export namespace IPointer { - /** - * Inference of value type. - */ - export type ValueType> = - Pointer extends IPointer ? T : unknown; + /** + * Inference of value type. + */ + export type ValueType> = + Pointer extends IPointer ? T : unknown; } diff --git a/src/functional/bit_operations.ts b/src/functional/bit_operations.ts index 1d0d47d7..c19c765c 100644 --- a/src/functional/bit_operations.ts +++ b/src/functional/bit_operations.ts @@ -5,25 +5,25 @@ */ //================================================================ export function logical_and(x: T, y: T): boolean { - return !!x && !!y; + return !!x && !!y; } export function logical_or(x: T, y: T): boolean { - return !!x || !!y; + return !!x || !!y; } export function logical_not(x: T): boolean { - return !x; + return !x; } export function bit_and(x: number, y: number): number { - return x & y; + return x & y; } export function bit_or(x: number, y: number): number { - return x | y; + return x | y; } export function bit_xor(x: number, y: number): number { - return x ^ y; + return x ^ y; } diff --git a/src/functional/comparators.ts b/src/functional/comparators.ts index acce1852..84c1c1b2 100644 --- a/src/functional/comparators.ts +++ b/src/functional/comparators.ts @@ -1,11 +1,11 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ import { IComparable } from "./IComparable"; - import { get_uid } from "./uid"; /** @@ -16,17 +16,17 @@ import { get_uid } from "./uid"; * @return Whether two arguments are equal or not. */ export function equal_to(x: T, y: T): boolean { - // CONVERT TO PRIMITIVE TYPE - x = x ? ((x as any).valueOf() as T) : x; - y = y ? ((y as any).valueOf() as T) : y; + // CONVERT TO PRIMITIVE TYPE + x = x ? ((x as any).valueOf() as T) : x; + y = y ? ((y as any).valueOf() as T) : y; - // DO COMPARE - if ( - x instanceof Object && - ((x) as IComparable).equals instanceof Function - ) - return ((x) as IComparable).equals(y); - else return x === y; + // DO COMPARE + if ( + x instanceof Object && + ((x) as IComparable).equals instanceof Function + ) + return ((x) as IComparable).equals(y); + else return x === y; } /** @@ -37,7 +37,7 @@ export function equal_to(x: T, y: T): boolean { * @return Returns `true`, if two arguments are not equal, otherwise `false`. */ export function not_equal_to(x: T, y: T): boolean { - return !equal_to(x, y); + return !equal_to(x, y); } /** @@ -48,17 +48,17 @@ export function not_equal_to(x: T, y: T): boolean { * @return Whether *x* is less than *y*. */ export function less(x: T, y: T): boolean { - // CONVERT TO PRIMITIVE TYPE - x = (x as any).valueOf() as T; - y = (y as any).valueOf() as T; + // CONVERT TO PRIMITIVE TYPE + x = (x as any).valueOf() as T; + y = (y as any).valueOf() as T; - // DO COMPARE - if (x instanceof Object) - if (((x) as IComparable).less instanceof Function) - // has less() - return ((x) as IComparable).less(y); - else return get_uid(x) < get_uid(y); - else return x < y; + // DO COMPARE + if (x instanceof Object) + if (((x) as IComparable).less instanceof Function) + // has less() + return ((x) as IComparable).less(y); + else return get_uid(x) < get_uid(y); + else return x < y; } /** @@ -69,7 +69,7 @@ export function less(x: T, y: T): boolean { * @return Whether *x* is less than or equal to *y*. */ export function less_equal(x: T, y: T): boolean { - return less(x, y) || equal_to(x, y); + return less(x, y) || equal_to(x, y); } /** @@ -80,7 +80,7 @@ export function less_equal(x: T, y: T): boolean { * @return Whether *x* is greater than *y*. */ export function greater(x: T, y: T): boolean { - return !less_equal(x, y); + return !less_equal(x, y); } /** @@ -91,5 +91,5 @@ export function greater(x: T, y: T): boolean { * @return Whether *x* is greater than or equal to *y*. */ export function greater_equal(x: T, y: T): boolean { - return !less(x, y); + return !less(x, y); } diff --git a/src/functional/hash.ts b/src/functional/hash.ts index 1f0fbf94..87b89d8c 100644 --- a/src/functional/hash.ts +++ b/src/functional/hash.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -14,73 +15,73 @@ import { get_uid } from "./uid"; * @return The hash code. */ export function hash(...itemList: any[]): number { - let ret: number = INIT_VALUE; + let ret: number = INIT_VALUE; - for (let item of itemList) { - item = item ? item.valueOf() : item; - const type: string = typeof item; + for (let item of itemList) { + item = item ? item.valueOf() : item; + const type: string = typeof item; - if (type === "boolean") - // BOOLEAN -> 1 BYTE - ret = _Hash_boolean(item, ret); - else if (type === "number" || type === "bigint") - // NUMBER -> 8 BYTES - ret = _Hash_number(item, ret); - else if (type === "string") - // STRING -> {LENGTH} BYTES - ret = _Hash_string(item, ret); - else if ( - item instanceof Object && - ((item) as IComparable<{}>).hashCode instanceof Function - ) { - const hashed: number = ((item) as IComparable<{}>).hashCode(); - if (itemList.length === 1) return hashed; - else { - ret = ret ^ hashed; - ret *= MULTIPLIER; - } - } // object | null | undefined - else ret = _Hash_number(get_uid(item), ret); - } - return Math.abs(ret); + if (type === "boolean") + // BOOLEAN -> 1 BYTE + ret = _Hash_boolean(item, ret); + else if (type === "number" || type === "bigint") + // NUMBER -> 8 BYTES + ret = _Hash_number(item, ret); + else if (type === "string") + // STRING -> {LENGTH} BYTES + ret = _Hash_string(item, ret); + else if ( + item instanceof Object && + ((item) as IComparable<{}>).hashCode instanceof Function + ) { + const hashed: number = ((item) as IComparable<{}>).hashCode(); + if (itemList.length === 1) return hashed; + else { + ret = ret ^ hashed; + ret *= MULTIPLIER; + } + } // object | null | undefined + else ret = _Hash_number(get_uid(item), ret); + } + return Math.abs(ret); } function _Hash_boolean(val: boolean, ret: number): number { - ret ^= val ? 1 : 0; - ret *= MULTIPLIER; + ret ^= val ? 1 : 0; + ret *= MULTIPLIER; - return ret; + return ret; } function _Hash_number(val: number, ret: number): number { - return _Hash_string(val.toString(), ret); - // // ------------------------------------------ - // // IN C++ - // // CONSIDER A NUMBER AS A STRING - // // HASH((CHAR*)&VAL, 8) - // // ------------------------------------------ - // // CONSTRUCT BUFFER AND BYTE_ARRAY - // const buffer: ArrayBuffer = new ArrayBuffer(8); - // const byteArray: Int8Array = new Int8Array(buffer); - // const valueArray: Float64Array = new Float64Array(buffer); - // valueArray[0] = val; + return _Hash_string(val.toString(), ret); + // // ------------------------------------------ + // // IN C++ + // // CONSIDER A NUMBER AS A STRING + // // HASH((CHAR*)&VAL, 8) + // // ------------------------------------------ + // // CONSTRUCT BUFFER AND BYTE_ARRAY + // const buffer: ArrayBuffer = new ArrayBuffer(8); + // const byteArray: Int8Array = new Int8Array(buffer); + // const valueArray: Float64Array = new Float64Array(buffer); + // valueArray[0] = val; - // for (let i: number = 0; i < byteArray.length; ++i) - // { - // const byte = (byteArray[i] < 0) ? byteArray[i] + 256 : byteArray[i]; + // for (let i: number = 0; i < byteArray.length; ++i) + // { + // const byte = (byteArray[i] < 0) ? byteArray[i] + 256 : byteArray[i]; - // ret ^= byte; - // ret *= _HASH_MULTIPLIER; - // } - // return Math.abs(ret); + // ret ^= byte; + // ret *= _HASH_MULTIPLIER; + // } + // return Math.abs(ret); } function _Hash_string(str: string, ret: number): number { - for (let i: number = 0; i < str.length; ++i) { - ret ^= str.charCodeAt(i); - ret *= MULTIPLIER; - } - return Math.abs(ret); + for (let i: number = 0; i < str.length; ++i) { + ret ^= str.charCodeAt(i); + ret *= MULTIPLIER; + } + return Math.abs(ret); } /* --------------------------------------------------------- diff --git a/src/functional/uid.ts b/src/functional/uid.ts index 1ea9e5c6..637d22b8 100644 --- a/src/functional/uid.ts +++ b/src/functional/uid.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -13,24 +14,24 @@ import { _Get_root } from "../internal/Global"; * @return The identifier number. */ export function get_uid(obj: object | null | undefined): number { - // NO UID EXISTS, THEN ISSUE ONE. - if (obj instanceof Object) { - if (obj.hasOwnProperty("__get_m_iUID") === false) { - const uid: number = ++_Get_root().__s_iUID; - Object.defineProperty(obj, "__get_m_iUID", { - value: function (): number { - return uid; - }, - }); - } + // NO UID EXISTS, THEN ISSUE ONE. + if (obj instanceof Object) { + if (obj.hasOwnProperty("__get_m_iUID") === false) { + const uid: number = ++_Get_root().__s_iUID; + Object.defineProperty(obj, "__get_m_iUID", { + value: function (): number { + return uid; + }, + }); + } - // RETURNS - return (obj as IObject).__get_m_iUID(); - } else if (obj === undefined) return -1; - // is null - else return 0; + // RETURNS + return (obj as IObject).__get_m_iUID(); + } else if (obj === undefined) return -1; + // is null + else return 0; } interface IObject { - readonly __get_m_iUID: () => number; + readonly __get_m_iUID: () => number; } diff --git a/src/index.ts b/src/index.ts index 704a11b7..650876c3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,5 @@ //================================================================ + /** * TSTL - TypeScript Standard Template Library * diff --git a/src/internal/Global.ts b/src/internal/Global.ts index 26dd6bdf..2c6f570e 100644 --- a/src/internal/Global.ts +++ b/src/internal/Global.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -10,19 +11,19 @@ import { is_node } from "../utility/node"; * @internal */ export interface IGlobal { - __s_iUID: number; - __s_pTerminate_handler?: () => void; + __s_iUID: number; + __s_pTerminate_handler?: () => void; } /** * @internal */ export function _Get_root(): IGlobal { - if (__s_pRoot === null) { - __s_pRoot = (is_node() ? global : self) as any; - if (__s_pRoot!.__s_iUID === undefined) __s_pRoot!.__s_iUID = 0; - } - return __s_pRoot!; + if (__s_pRoot === null) { + __s_pRoot = (is_node() ? global : self) as any; + if (__s_pRoot!.__s_iUID === undefined) __s_pRoot!.__s_iUID = 0; + } + return __s_pRoot!; } /** diff --git a/src/internal/container/associative/IAssociativeContainer.ts b/src/internal/container/associative/IAssociativeContainer.ts index ad4cb23e..1e00aed3 100644 --- a/src/internal/container/associative/IAssociativeContainer.ts +++ b/src/internal/container/associative/IAssociativeContainer.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -12,135 +13,135 @@ import { IContainer } from "../../../base/container/IContainer"; * @author Jeongho Nam - https://github.com/samchon */ export interface IAssociativeContainer< + Key, + T extends Elem, + SourceT extends IAssociativeContainer< Key, - T extends Elem, - SourceT extends IAssociativeContainer< - Key, - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - IteratorT extends IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - ReverseIteratorT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - Elem, + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + IteratorT extends IContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + ReverseIteratorT extends IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + Elem, > extends IContainer { - /** - * Get iterator to element. - * - * @param key Key to search for. - * @return An iterator to the element, if the specified key is found, otherwise `this.end()`. - */ - find(key: Key): IteratorT; + /** + * Get iterator to element. + * + * @param key Key to search for. + * @return An iterator to the element, if the specified key is found, otherwise `this.end()`. + */ + find(key: Key): IteratorT; - /** - * Test whether a key exists. - * - * @param key Key to search for. - * @return Whether the specified key exists. - */ - has(key: Key): boolean; + /** + * Test whether a key exists. + * + * @param key Key to search for. + * @return Whether the specified key exists. + */ + has(key: Key): boolean; - /** - * Count elements with a specified key. - * - * @param key Key to search for. - * @return Number of elements with the specified key. - */ - count(key: Key): number; + /** + * Count elements with a specified key. + * + * @param key Key to search for. + * @return Number of elements with the specified key. + */ + count(key: Key): number; - /** - * Erase elements with a specified key. - * - * @param key Key to search for. - * @return Number of erased elements. - */ - erase(key: Key): number; + /** + * Erase elements with a specified key. + * + * @param key Key to search for. + * @return Number of erased elements. + */ + erase(key: Key): number; - /** - * @inheritDoc - */ - erase(pos: IteratorT): IteratorT; + /** + * @inheritDoc + */ + erase(pos: IteratorT): IteratorT; - /** - * @inheritDoc - */ - erase(first: IteratorT, last: IteratorT): IteratorT; + /** + * @inheritDoc + */ + erase(first: IteratorT, last: IteratorT): IteratorT; } export namespace IAssociativeContainer { - /** - * @internal - */ - export function construct< - Key, - T extends Elem, - SourceT extends IAssociativeContainer< - Key, - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - IteratorT extends IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - ReverseIteratorT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - Elem, - >(source: SourceT, ...args: any[]) { - let ramda: (() => void) | null; - let tail: any[]; - - if (args.length >= 1 && args[0] instanceof Array) { - // INITIALIZER LIST CONSTRUCTOR - ramda = () => { - const items: Elem[] = args[0]; - source.push(...items); - }; - tail = args.slice(1); - } else if ( - args.length >= 2 && - args[0].next instanceof Function && - args[1].next instanceof Function - ) { - // RANGE CONSTRUCTOR - ramda = () => { - const first: IteratorT = args[0]; - const last: IteratorT = args[1]; + /** + * @internal + */ + export function construct< + Key, + T extends Elem, + SourceT extends IAssociativeContainer< + Key, + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + IteratorT extends IContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + ReverseIteratorT extends IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + Elem, + >(source: SourceT, ...args: any[]) { + let ramda: (() => void) | null; + let tail: any[]; - source.assign(first, last); - }; - tail = args.slice(2); - } else { - // DEFAULT CONSTRUCTOR - ramda = null; - tail = args; - } + if (args.length >= 1 && args[0] instanceof Array) { + // INITIALIZER LIST CONSTRUCTOR + ramda = () => { + const items: Elem[] = args[0]; + source.push(...items); + }; + tail = args.slice(1); + } else if ( + args.length >= 2 && + args[0].next instanceof Function && + args[1].next instanceof Function + ) { + // RANGE CONSTRUCTOR + ramda = () => { + const first: IteratorT = args[0]; + const last: IteratorT = args[1]; - return { ramda: ramda, tail: tail }; + source.assign(first, last); + }; + tail = args.slice(2); + } else { + // DEFAULT CONSTRUCTOR + ramda = null; + tail = args; } + + return { ramda: ramda, tail: tail }; + } } diff --git a/src/internal/container/associative/IHashContainer.ts b/src/internal/container/associative/IHashContainer.ts index e6aa0c4d..5d113a75 100644 --- a/src/internal/container/associative/IHashContainer.ts +++ b/src/internal/container/associative/IHashContainer.ts @@ -1,17 +1,16 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { IAssociativeContainer } from "./IAssociativeContainer"; - import { IContainer } from "../../../base/container/IContainer"; -import { Hasher } from "../../functional/Hasher"; -import { BinaryPredicator } from "../../functional/BinaryPredicator"; - -import { hash } from "../../../functional/hash"; import { equal_to } from "../../../functional/comparators"; +import { hash } from "../../../functional/hash"; +import { BinaryPredicator } from "../../functional/BinaryPredicator"; +import { Hasher } from "../../functional/Hasher"; +import { IAssociativeContainer } from "./IAssociativeContainer"; /** * Common interface for hash containers @@ -19,203 +18,203 @@ import { equal_to } from "../../../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export interface IHashContainer< + Key, + T extends Elem, + SourceT extends IHashContainer< Key, - T extends Elem, - SourceT extends IHashContainer< - Key, - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - IteratorT extends IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - ReverseIteratorT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - Elem, + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + IteratorT extends IContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + ReverseIteratorT extends IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + Elem, > extends IAssociativeContainer< - Key, - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - > { - /* --------------------------------------------------------- + Key, + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + > { + /* --------------------------------------------------------- PREDICATORS --------------------------------------------------------- */ - /** - * Get hash function. - * - * @return The hash function. - */ - hash_function(): Hasher; - - /** - * Get key equality predicator. - * - * @return The key equality predicator. - */ - key_eq(): BinaryPredicator; - - /* --------------------------------------------------------- + /** + * Get hash function. + * + * @return The hash function. + */ + hash_function(): Hasher; + + /** + * Get key equality predicator. + * + * @return The key equality predicator. + */ + key_eq(): BinaryPredicator; + + /* --------------------------------------------------------- GETTERS --------------------------------------------------------- */ - /** - * Compute bucket index for the *key*. - * - * @param key Target key. - * @return Index number. - */ - bucket(key: Key): number; - - /** - * Get number of buckets. - */ - bucket_count(): number; - - /** - * Get size of a specific bucket. - * - * @param index Specific position. - * @return Size of the specific bucket. - */ - bucket_size(index: number): number; - - /** - * Compute load factor. - * - * @return `this.size() / this.bucket_count()` - */ - load_factor(): number; - - /** - * Get maximum load factor that allowable. - * - * @return The maximum load factor. - */ - max_load_factor(): number; - - /* --------------------------------------------------------- + /** + * Compute bucket index for the *key*. + * + * @param key Target key. + * @return Index number. + */ + bucket(key: Key): number; + + /** + * Get number of buckets. + */ + bucket_count(): number; + + /** + * Get size of a specific bucket. + * + * @param index Specific position. + * @return Size of the specific bucket. + */ + bucket_size(index: number): number; + + /** + * Compute load factor. + * + * @return `this.size() / this.bucket_count()` + */ + load_factor(): number; + + /** + * Get maximum load factor that allowable. + * + * @return The maximum load factor. + */ + max_load_factor(): number; + + /* --------------------------------------------------------- SETTERS --------------------------------------------------------- */ - /** - * Set maximum load factor. - * - * @param z The new value to change. - */ - max_load_factor(z: number): void; - - /** - * Reserve buckets enable to store *n* elements. - * - * @param n The capacity to reserve. - */ - reserve(n: number): void; - - /** - * Change of bucktes. - * - * @param n The number to change. - */ - rehash(n: number): void; + /** + * Set maximum load factor. + * + * @param z The new value to change. + */ + max_load_factor(z: number): void; + + /** + * Reserve buckets enable to store *n* elements. + * + * @param n The capacity to reserve. + */ + reserve(n: number): void; + + /** + * Change of bucktes. + * + * @param n The number to change. + */ + rehash(n: number): void; } export namespace IHashContainer { - /** - * @internal - */ - export function construct< - Key, - T extends Elem, - SourceT extends IHashContainer< - Key, - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - IteratorT extends IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - ReverseIteratorT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - Elem, - >( - source: SourceT, - Source: Factory, - bucketFactory: ( - hasher: Hasher, - predicator: BinaryPredicator, - ) => void, - ...args: any[] - ) { - // DECLARE MEMBERS - let post_process: (() => void) | null = null; - let hash_function: Hasher = hash; - let key_eq: BinaryPredicator = equal_to; - - //---- - // INITIALIZE MEMBERS AND POST-PROCESS - //---- - // BRANCH - METHOD OVERLOADINGS - if (args.length === 1 && args[0] instanceof Source) { - // PARAMETERS - const container: SourceT = args[0]; - hash_function = container.hash_function(); - key_eq = container.key_eq(); - - // COPY CONSTRUCTOR - post_process = () => { - const first = container.begin(); - const last = container.end(); - - source.assign(first, last); - }; - } else { - const tuple = IAssociativeContainer.construct(source, ...args); - - post_process = tuple.ramda; - if (tuple.tail.length >= 1) hash_function = tuple.tail[0]; - if (tuple.tail.length >= 2) key_eq = tuple.tail[1]; - } - - //---- - // DO PROCESS - //---- - // CONSTRUCT BUCKET - bucketFactory(hash_function, key_eq); - - // ACT POST-PROCESS - if (post_process !== null) post_process(); + /** + * @internal + */ + export function construct< + Key, + T extends Elem, + SourceT extends IHashContainer< + Key, + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + IteratorT extends IContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + ReverseIteratorT extends IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + Elem, + >( + source: SourceT, + Source: Factory, + bucketFactory: ( + hasher: Hasher, + predicator: BinaryPredicator, + ) => void, + ...args: any[] + ) { + // DECLARE MEMBERS + let post_process: (() => void) | null = null; + let hash_function: Hasher = hash; + let key_eq: BinaryPredicator = equal_to; + + //---- + // INITIALIZE MEMBERS AND POST-PROCESS + //---- + // BRANCH - METHOD OVERLOADINGS + if (args.length === 1 && args[0] instanceof Source) { + // PARAMETERS + const container: SourceT = args[0]; + hash_function = container.hash_function(); + key_eq = container.key_eq(); + + // COPY CONSTRUCTOR + post_process = () => { + const first = container.begin(); + const last = container.end(); + + source.assign(first, last); + }; + } else { + const tuple = IAssociativeContainer.construct(source, ...args); + + post_process = tuple.ramda; + if (tuple.tail.length >= 1) hash_function = tuple.tail[0]; + if (tuple.tail.length >= 2) key_eq = tuple.tail[1]; } - /** - * @internal - */ - interface Factory { - new (...args: Arguments): T; - prototype: T; - } + //---- + // DO PROCESS + //---- + // CONSTRUCT BUCKET + bucketFactory(hash_function, key_eq); + + // ACT POST-PROCESS + if (post_process !== null) post_process(); + } + + /** + * @internal + */ + interface Factory { + new (...args: Arguments): T; + prototype: T; + } } diff --git a/src/internal/container/associative/ITreeContainer.ts b/src/internal/container/associative/ITreeContainer.ts index 773cb1a9..423d70f7 100644 --- a/src/internal/container/associative/ITreeContainer.ts +++ b/src/internal/container/associative/ITreeContainer.ts @@ -1,15 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { IAssociativeContainer } from "./IAssociativeContainer"; - import { IContainer } from "../../../base/container/IContainer"; -import { Comparator } from "../../functional/Comparator"; -import { Pair } from "../../../utility/Pair"; import { less } from "../../../functional/comparators"; +import { Pair } from "../../../utility/Pair"; +import { Comparator } from "../../functional/Comparator"; +import { IAssociativeContainer } from "./IAssociativeContainer"; /** * Common interface for tree containers. @@ -17,197 +17,196 @@ import { less } from "../../../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export interface ITreeContainer< + Key, + T extends Elem, + SourceT extends ITreeContainer< + Key, + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + IteratorT extends IContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + ReverseIteratorT extends IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + Elem, +> extends IAssociativeContainer< + Key, + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + > { + /** + * Get key comparison function. + * + * @return The key comparison function. + */ + key_comp(): Comparator; + + /** + * Get value comparison function. + * + * @return The value comparison function. + */ + value_comp(): Comparator; + + /** + * Get iterator to lower bound. + * + * @param key Key to search for. + * @return Iterator to the first element equal or after to the key. + */ + lower_bound(key: Key): IteratorT; + + /** + * Get iterator to upper bound. + * + * @param key Key to search for. + * @return Iterator to the first element after the key. + */ + upper_bound(key: Key): IteratorT; + + /** + * Get range of equal elements. + * + * @param key Key to search for. + * @return Pair of {@link lower_bound} and {@link upper_bound}. + */ + equal_range(key: Key): Pair; +} + +export namespace ITreeContainer { + /** + * @internal + */ + export function construct< Key, T extends Elem, SourceT extends ITreeContainer< - Key, - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem + Key, + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem >, IteratorT extends IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem >, ReverseIteratorT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem >, Elem, -> extends IAssociativeContainer< - Key, - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - > { - /** - * Get key comparison function. - * - * @return The key comparison function. - */ - key_comp(): Comparator; - - /** - * Get value comparison function. - * - * @return The value comparison function. - */ - value_comp(): Comparator; - - /** - * Get iterator to lower bound. - * - * @param key Key to search for. - * @return Iterator to the first element equal or after to the key. - */ - lower_bound(key: Key): IteratorT; - - /** - * Get iterator to upper bound. - * - * @param key Key to search for. - * @return Iterator to the first element after the key. - */ - upper_bound(key: Key): IteratorT; - - /** - * Get range of equal elements. - * - * @param key Key to search for. - * @return Pair of {@link lower_bound} and {@link upper_bound}. - */ - equal_range(key: Key): Pair; -} - -export namespace ITreeContainer { - /** - * @internal - */ - export function construct< - Key, - T extends Elem, - SourceT extends ITreeContainer< - Key, - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - IteratorT extends IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - ReverseIteratorT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - Elem, - >( - source: SourceT, - Source: Factory, - treeFactory: (comp: Comparator) => void, - ...args: any[] - ) { - // DECLARE MEMBERS - let post_process: (() => void) | null = null; - let comp: Comparator = less; - - //---- - // INITIALIZE MEMBERS AND POST-PROCESS - //---- - // BRANCH - METHOD OVERLOADINGS - if (args.length === 1 && args[0] instanceof Source) { - // PARAMETERS - const container: SourceT = args[0]; - comp = container.key_comp(); - - // COPY CONSTRUCTOR - post_process = () => { - const first = container.begin(); - const last = container.end(); - - source.assign(first, last); - }; - } else { - const tuple = IAssociativeContainer.construct(source, ...args); - - post_process = tuple.ramda; - if (tuple.tail.length >= 1) comp = tuple.tail[0]; - } - - //---- - // DO PROCESS - //---- - // CONSTRUCT TREE - treeFactory(comp); - - // ACT POST-PROCESS - if (post_process !== null) post_process(); + >( + source: SourceT, + Source: Factory, + treeFactory: (comp: Comparator) => void, + ...args: any[] + ) { + // DECLARE MEMBERS + let post_process: (() => void) | null = null; + let comp: Comparator = less; + + //---- + // INITIALIZE MEMBERS AND POST-PROCESS + //---- + // BRANCH - METHOD OVERLOADINGS + if (args.length === 1 && args[0] instanceof Source) { + // PARAMETERS + const container: SourceT = args[0]; + comp = container.key_comp(); + + // COPY CONSTRUCTOR + post_process = () => { + const first = container.begin(); + const last = container.end(); + + source.assign(first, last); + }; + } else { + const tuple = IAssociativeContainer.construct(source, ...args); + + post_process = tuple.ramda; + if (tuple.tail.length >= 1) comp = tuple.tail[0]; } - /** - * @internal - */ - export function emplacable< - Key, - T extends Elem, - SourceT extends ITreeContainer< - Key, - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - IteratorT extends IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - ReverseIteratorT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - Elem, - >(source: SourceT, hint: IteratorT, elem: T): boolean { - const prev = hint.prev(); - let meet: boolean = - prev.equals(source.end()) || source.value_comp()(prev.value, elem); - meet = - meet && - (hint.equals(source.end()) || - source.value_comp()(elem, hint.value)); - - return meet; - } + //---- + // DO PROCESS + //---- + // CONSTRUCT TREE + treeFactory(comp); - /** - * @internal - */ - interface Factory { - new (...args: Arguments): T; - prototype: T; - } + // ACT POST-PROCESS + if (post_process !== null) post_process(); + } + + /** + * @internal + */ + export function emplacable< + Key, + T extends Elem, + SourceT extends ITreeContainer< + Key, + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + IteratorT extends IContainer.Iterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + ReverseIteratorT extends IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + Elem, + >(source: SourceT, hint: IteratorT, elem: T): boolean { + const prev = hint.prev(); + let meet: boolean = + prev.equals(source.end()) || source.value_comp()(prev.value, elem); + meet = + meet && + (hint.equals(source.end()) || source.value_comp()(elem, hint.value)); + + return meet; + } + + /** + * @internal + */ + interface Factory { + new (...args: Arguments): T; + prototype: T; + } } diff --git a/src/internal/container/associative/MapElementList.ts b/src/internal/container/associative/MapElementList.ts index 1dc71256..d97730c5 100644 --- a/src/internal/container/associative/MapElementList.ts +++ b/src/internal/container/associative/MapElementList.ts @@ -1,16 +1,16 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { ListContainer } from "../linear/ListContainer"; -import { ListIterator } from "../../iterator/ListIterator"; -import { ReverseIterator as _ReverseIterator } from "../../iterator/ReverseIterator"; - import { MapContainer } from "../../../base/container/MapContainer"; -import { IPair } from "../../../utility/IPair"; import { Entry } from "../../../utility/Entry"; +import { IPair } from "../../../utility/IPair"; +import { ListIterator } from "../../iterator/ListIterator"; +import { ReverseIterator as _ReverseIterator } from "../../iterator/ReverseIterator"; +import { ListContainer } from "../linear/ListContainer"; /** * Doubly Linked List storing map elements. @@ -23,271 +23,271 @@ import { Entry } from "../../../utility/Entry"; * @author Jeongho Nam - https://github.com/samchon */ export class MapElementList< + Key, + T, + Unique extends boolean, + Source extends MapContainer< Key, T, - Unique extends boolean, - Source extends MapContainer< - Key, - T, - Unique, - Source, - MapElementList.Iterator, - MapElementList.ReverseIterator - >, -> extends ListContainer< - Entry, + Unique, Source, MapElementList.Iterator, MapElementList.ReverseIterator + >, +> extends ListContainer< + Entry, + Source, + MapElementList.Iterator, + MapElementList.ReverseIterator > { - private associative_: Source; + private associative_: Source; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - public constructor(associative: Source) { - super(); + public constructor(associative: Source) { + super(); - this.associative_ = associative; - } + this.associative_ = associative; + } - protected _Create_iterator( - prev: MapElementList.Iterator, - next: MapElementList.Iterator, - val: Entry, - ): MapElementList.Iterator { - return MapElementList.Iterator.create(this, prev, next, val); - } + protected _Create_iterator( + prev: MapElementList.Iterator, + next: MapElementList.Iterator, + val: Entry, + ): MapElementList.Iterator { + return MapElementList.Iterator.create(this, prev, next, val); + } - /** - * @internal - */ - public static _Swap_associative< - Key, - T, - Unique extends boolean, - Source extends MapContainer< - Key, - T, - Unique, - Source, - MapElementList.Iterator, - MapElementList.ReverseIterator - >, - >( - x: MapElementList, - y: MapElementList, - ): void { - [x.associative_, y.associative_] = [y.associative_, x.associative_]; - } + /** + * @internal + */ + public static _Swap_associative< + Key, + T, + Unique extends boolean, + Source extends MapContainer< + Key, + T, + Unique, + Source, + MapElementList.Iterator, + MapElementList.ReverseIterator + >, + >( + x: MapElementList, + y: MapElementList, + ): void { + [x.associative_, y.associative_] = [y.associative_, x.associative_]; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - public associative(): Source { - return this.associative_; - } + public associative(): Source { + return this.associative_; + } } /** * */ export namespace MapElementList { - /** - * Iterator of map container storing elements in a list. - * - * @template Key Key type - * @template T Mapped type - * @template Unique Whether duplicated key is blocked or not - * @template Source Source container type - * - * @author Jeongho Nam - https://github.com/samchon - */ - export class Iterator< - Key, - T, - Unique extends boolean, - Source extends MapContainer< - Key, - T, - Unique, - Source, - Iterator, - ReverseIterator - >, - > - extends ListIterator< - Entry, - Source, - Iterator, - ReverseIterator, - IPair - > - implements - MapContainer.Iterator< - Key, - T, - Unique, - Source, - Iterator, - ReverseIterator - > - { - private list_: MapElementList; + /** + * Iterator of map container storing elements in a list. + * + * @template Key Key type + * @template T Mapped type + * @template Unique Whether duplicated key is blocked or not + * @template Source Source container type + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class Iterator< + Key, + T, + Unique extends boolean, + Source extends MapContainer< + Key, + T, + Unique, + Source, + Iterator, + ReverseIterator + >, + > + extends ListIterator< + Entry, + Source, + Iterator, + ReverseIterator, + IPair + > + implements + MapContainer.Iterator< + Key, + T, + Unique, + Source, + Iterator, + ReverseIterator + > + { + private list_: MapElementList; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - private constructor( - list: MapElementList, - prev: Iterator, - next: Iterator, - val: Entry, - ) { - super(prev, next, val); - this.list_ = list; - } + private constructor( + list: MapElementList, + prev: Iterator, + next: Iterator, + val: Entry, + ) { + super(prev, next, val); + this.list_ = list; + } - /** - * @internal - */ - public static create< - Key, - T, - Unique extends boolean, - Source extends MapContainer< - Key, - T, - Unique, - Source, - Iterator, - ReverseIterator - >, - >( - list: MapElementList, - prev: Iterator, - next: Iterator, - val: Entry, - ) { - return new Iterator(list, prev, next, val); - } + /** + * @internal + */ + public static create< + Key, + T, + Unique extends boolean, + Source extends MapContainer< + Key, + T, + Unique, + Source, + Iterator, + ReverseIterator + >, + >( + list: MapElementList, + prev: Iterator, + next: Iterator, + val: Entry, + ) { + return new Iterator(list, prev, next, val); + } - /** - * @inheritDoc - */ - public reverse(): ReverseIterator { - return new ReverseIterator(this); - } + /** + * @inheritDoc + */ + public reverse(): ReverseIterator { + return new ReverseIterator(this); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public source(): Source { - return this.list_.associative(); - } - - /** - * @inheritDoc - */ - public get first(): Key { - return this.value.first; - } + /** + * @inheritDoc + */ + public source(): Source { + return this.list_.associative(); + } - /** - * @inheritDoc - */ - public get second(): T { - return this.value.second; - } + /** + * @inheritDoc + */ + public get first(): Key { + return this.value.first; + } - /** - * @inheritDoc - */ - public set second(val: T) { - this.value.second = val; - } + /** + * @inheritDoc + */ + public get second(): T { + return this.value.second; } /** - * Reverse iterator of map container storing elements a list. - * - * @template Key Key type - * @template T Mapped type - * @template Unique Whether duplicated key is blocked or not - * @template Source Source container type - * - * @author Jeongho Nam - https://github.com/samchon + * @inheritDoc */ - export class ReverseIterator< - Key, - T, - Unique extends boolean, - Source extends MapContainer< - Key, - T, - Unique, - Source, - Iterator, - ReverseIterator - >, - > - extends _ReverseIterator< - Entry, - Source, - Iterator, - ReverseIterator, - IPair - > - implements - MapContainer.ReverseIterator< - Key, - T, - Unique, - Source, - Iterator, - ReverseIterator - > - { - /* --------------------------------------------------------- + public set second(val: T) { + this.value.second = val; + } + } + + /** + * Reverse iterator of map container storing elements a list. + * + * @template Key Key type + * @template T Mapped type + * @template Unique Whether duplicated key is blocked or not + * @template Source Source container type + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class ReverseIterator< + Key, + T, + Unique extends boolean, + Source extends MapContainer< + Key, + T, + Unique, + Source, + Iterator, + ReverseIterator + >, + > + extends _ReverseIterator< + Entry, + Source, + Iterator, + ReverseIterator, + IPair + > + implements + MapContainer.ReverseIterator< + Key, + T, + Unique, + Source, + Iterator, + ReverseIterator + > + { + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - protected _Create_neighbor( - base: Iterator, - ): ReverseIterator { - return new ReverseIterator(base); - } + protected _Create_neighbor( + base: Iterator, + ): ReverseIterator { + return new ReverseIterator(base); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * Get the first, key element. - * - * @return The first element. - */ - public get first(): Key { - return this.base_.first; - } + /** + * Get the first, key element. + * + * @return The first element. + */ + public get first(): Key { + return this.base_.first; + } - /** - * Get the second, stored element. - * - * @return The second element. - */ - public get second(): T { - return this.base_.second; - } + /** + * Get the second, stored element. + * + * @return The second element. + */ + public get second(): T { + return this.base_.second; + } - /** - * Set the second, stored element. - * - * @param val The value to set. - */ - public set second(val: T) { - this.base_.second = val; - } + /** + * Set the second, stored element. + * + * @param val The value to set. + */ + public set second(val: T) { + this.base_.second = val; } + } } diff --git a/src/internal/container/associative/MapElementVector.ts b/src/internal/container/associative/MapElementVector.ts index 7d82abdf..1c53f0dd 100644 --- a/src/internal/container/associative/MapElementVector.ts +++ b/src/internal/container/associative/MapElementVector.ts @@ -1,16 +1,16 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { VectorContainer } from "../linear/VectorContainer"; -import { ArrayIteratorBase } from "../../iterator/ArrayIteratorBase"; -import { ArrayReverseIteratorBase } from "../../iterator/ArrayReverseIteratorBase"; - import { ITreeMap } from "../../../base/container/ITreeMap"; -import { IPair } from "../../../utility/IPair"; import { Entry } from "../../../utility/Entry"; +import { IPair } from "../../../utility/IPair"; +import { ArrayIteratorBase } from "../../iterator/ArrayIteratorBase"; +import { ArrayReverseIteratorBase } from "../../iterator/ArrayReverseIteratorBase"; +import { VectorContainer } from "../linear/VectorContainer"; /** * Vector storing map elements. @@ -23,231 +23,229 @@ import { Entry } from "../../../utility/Entry"; * @author Jeongho Nam - https://github.com/samchon */ export class MapElementVector< + Key, + T, + Unique extends boolean, + Source extends ITreeMap< Key, T, - Unique extends boolean, - Source extends ITreeMap< - Key, - T, - Unique, - Source, - MapElementVector.Iterator, - MapElementVector.ReverseIterator - >, -> extends VectorContainer< - Entry, + Unique, Source, - MapElementVector, MapElementVector.Iterator, MapElementVector.ReverseIterator + >, +> extends VectorContainer< + Entry, + Source, + MapElementVector, + MapElementVector.Iterator, + MapElementVector.ReverseIterator > { - private associative_: Source; + private associative_: Source; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - public constructor(associative: Source) { - super(); + public constructor(associative: Source) { + super(); - this.data_ = []; - this.associative_ = associative; - } + this.data_ = []; + this.associative_ = associative; + } - public nth( - index: number, - ): MapElementVector.Iterator { - return new MapElementVector.Iterator(this, index); - } + public nth(index: number): MapElementVector.Iterator { + return new MapElementVector.Iterator(this, index); + } - /** - * @internal - */ - public static _Swap_associative< - Key, - T, - Unique extends boolean, - Source extends ITreeMap< - Key, - T, - Unique, - Source, - MapElementVector.Iterator, - MapElementVector.ReverseIterator - >, - >( - x: MapElementVector, - y: MapElementVector, - ): void { - [x.associative_, y.associative_] = [y.associative_, x.associative_]; - } - - /* --------------------------------------------------------- + /** + * @internal + */ + public static _Swap_associative< + Key, + T, + Unique extends boolean, + Source extends ITreeMap< + Key, + T, + Unique, + Source, + MapElementVector.Iterator, + MapElementVector.ReverseIterator + >, + >( + x: MapElementVector, + y: MapElementVector, + ): void { + [x.associative_, y.associative_] = [y.associative_, x.associative_]; + } + + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - public source(): Source { - return this.associative_; - } + public source(): Source { + return this.associative_; + } } /** * */ export namespace MapElementVector { - /** - * Iterator of map container storing elements in a vector. - * - * @template Key Key type - * @template T Mapped type - * @template Unique Whether duplicated key is blocked or not - * @template Source Source container type - * - * @author Jeongho Nam - https://github.com/samchon - */ - export class Iterator< - Key, - T, - Unique extends boolean, - Source extends ITreeMap< - Key, - T, - Unique, - Source, - Iterator, - ReverseIterator - >, - > - extends ArrayIteratorBase< - Entry, - Source, - MapElementVector, - Iterator, - ReverseIterator, - IPair - > - implements - ITreeMap.Iterator< - Key, - T, - Unique, - Source, - Iterator, - ReverseIterator - > - { - /* --------------------------------------------------------- + /** + * Iterator of map container storing elements in a vector. + * + * @template Key Key type + * @template T Mapped type + * @template Unique Whether duplicated key is blocked or not + * @template Source Source container type + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class Iterator< + Key, + T, + Unique extends boolean, + Source extends ITreeMap< + Key, + T, + Unique, + Source, + Iterator, + ReverseIterator + >, + > + extends ArrayIteratorBase< + Entry, + Source, + MapElementVector, + Iterator, + ReverseIterator, + IPair + > + implements + ITreeMap.Iterator< + Key, + T, + Unique, + Source, + Iterator, + ReverseIterator + > + { + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public source(): Source { - return this._Get_array().source(); - } - - /** - * @inheritDoc - */ - public reverse(): ReverseIterator { - return new ReverseIterator(this); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public source(): Source { + return this._Get_array().source(); + } + + /** + * @inheritDoc + */ + public reverse(): ReverseIterator { + return new ReverseIterator(this); + } + + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public get first(): Key { - return this.value.first; - } - - /** - * @inheritDoc - */ - public get second(): T { - return this.value.second; - } - - /** - * @inheritDoc - */ - public set second(val: T) { - this.value.second = val; - } + /** + * @inheritDoc + */ + public get first(): Key { + return this.value.first; } /** - * Reverse iterator of map container storing elements in a vector. - * - * @template Key Key type - * @template T Mapped type - * @template Unique Whether duplicated key is blocked or not - * @template Source Source container type - * - * @author Jeongho Nam - https://github.com/samchon + * @inheritDoc */ - export class ReverseIterator< - Key, - T, - Unique extends boolean, - Source extends ITreeMap< - Key, - T, - Unique, - Source, - Iterator, - ReverseIterator - >, - > - extends ArrayReverseIteratorBase< - Entry, - Source, - MapElementVector, - Iterator, - ReverseIterator, - IPair - > - implements - ITreeMap.ReverseIterator< - Key, - T, - Unique, - Source, - Iterator, - ReverseIterator - > - { - /* --------------------------------------------------------- + public get second(): T { + return this.value.second; + } + + /** + * @inheritDoc + */ + public set second(val: T) { + this.value.second = val; + } + } + + /** + * Reverse iterator of map container storing elements in a vector. + * + * @template Key Key type + * @template T Mapped type + * @template Unique Whether duplicated key is blocked or not + * @template Source Source container type + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class ReverseIterator< + Key, + T, + Unique extends boolean, + Source extends ITreeMap< + Key, + T, + Unique, + Source, + Iterator, + ReverseIterator + >, + > + extends ArrayReverseIteratorBase< + Entry, + Source, + MapElementVector, + Iterator, + ReverseIterator, + IPair + > + implements + ITreeMap.ReverseIterator< + Key, + T, + Unique, + Source, + Iterator, + ReverseIterator + > + { + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - protected _Create_neighbor( - base: Iterator, - ): ReverseIterator { - return new ReverseIterator(base); - } + protected _Create_neighbor( + base: Iterator, + ): ReverseIterator { + return new ReverseIterator(base); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public get first(): Key { - return this.value.first; - } - - /** - * @inheritDoc - */ - public get second(): T { - return this.value.second; - } - - /** - * @inheritDoc - */ - public set second(val: T) { - this.value.second = val; - } + /** + * @inheritDoc + */ + public get first(): Key { + return this.value.first; + } + + /** + * @inheritDoc + */ + public get second(): T { + return this.value.second; + } + + /** + * @inheritDoc + */ + public set second(val: T) { + this.value.second = val; } + } } diff --git a/src/internal/container/associative/MultiTreeMap.ts b/src/internal/container/associative/MultiTreeMap.ts index fe215504..8dfce433 100644 --- a/src/internal/container/associative/MultiTreeMap.ts +++ b/src/internal/container/associative/MultiTreeMap.ts @@ -1,19 +1,18 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ import { MultiMap } from "../../../base/container/MultiMap"; -import { ITreeContainer } from "./ITreeContainer"; - import { IForwardIterator } from "../../../iterator/IForwardIterator"; -import { IPair } from "../../../utility/IPair"; import { Entry } from "../../../utility/Entry"; +import { IPair } from "../../../utility/IPair"; import { Pair } from "../../../utility/Pair"; - import { Comparator } from "../../functional/Comparator"; import { Temporary } from "../../functional/Temporary"; +import { ITreeContainer } from "./ITreeContainer"; /** * Basic tree map allowing duplicated keys. @@ -27,142 +26,136 @@ import { Temporary } from "../../functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class MultiTreeMap< - Key, - T, - Source extends MultiTreeMap, - IteratorT extends MultiMap.Iterator< - Key, - T, - Source, - IteratorT, - ReverseT - >, - ReverseT extends MultiMap.ReverseIterator< - Key, - T, - Source, - IteratorT, - ReverseT - >, + Key, + T, + Source extends MultiTreeMap, + IteratorT extends MultiMap.Iterator, + ReverseT extends MultiMap.ReverseIterator< + Key, + T, + Source, + IteratorT, + ReverseT + >, + > + extends MultiMap + implements + ITreeContainer< + Key, + Entry, + Source, + IteratorT, + ReverseT, + IPair > - extends MultiMap - implements - ITreeContainer< - Key, - Entry, - Source, - IteratorT, - ReverseT, - IPair - > { - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public find(key: Key): IteratorT { - const it: IteratorT = this.lower_bound(key); - if (!it.equals(this.end()) && this._Key_eq(key, it.first)) return it; - else return this.end(); - } - - /** - * @inheritDoc - */ - public count(key: Key): number { - let it: IteratorT = this.find(key); - let ret: number = 0; - - for ( - ; - !it.equals(this.end()) && this._Key_eq(it.first, key); - it = it.next() - ) - ++ret; - - return ret; - } - - /** - * @inheritDoc - */ - public abstract lower_bound(key: Key): IteratorT; - - /** - * @inheritDoc - */ - public abstract upper_bound(key: Key): IteratorT; - - /** - * @inheritDoc - */ - public equal_range(key: Key): Pair { - return new Pair(this.lower_bound(key), this.upper_bound(key)); - } - - /** - * @inheritDoc - */ - public abstract key_comp(): Comparator; - - /** - * @inheritDoc - */ - public value_comp(): Comparator> { - return (x, y) => this.key_comp()(x.first, y.first); - } - - protected _Key_eq(x: Key, y: Key): boolean { - return !this.key_comp()(x, y) && !this.key_comp()(y, x); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public find(key: Key): IteratorT { + const it: IteratorT = this.lower_bound(key); + if (!it.equals(this.end()) && this._Key_eq(key, it.first)) return it; + else return this.end(); + } + + /** + * @inheritDoc + */ + public count(key: Key): number { + let it: IteratorT = this.find(key); + let ret: number = 0; + + for ( + ; + !it.equals(this.end()) && this._Key_eq(it.first, key); + it = it.next() + ) + ++ret; + + return ret; + } + + /** + * @inheritDoc + */ + public abstract lower_bound(key: Key): IteratorT; + + /** + * @inheritDoc + */ + public abstract upper_bound(key: Key): IteratorT; + + /** + * @inheritDoc + */ + public equal_range(key: Key): Pair { + return new Pair(this.lower_bound(key), this.upper_bound(key)); + } + + /** + * @inheritDoc + */ + public abstract key_comp(): Comparator; + + /** + * @inheritDoc + */ + public value_comp(): Comparator> { + return (x, y) => this.key_comp()(x.first, y.first); + } + + protected _Key_eq(x: Key, y: Key): boolean { + return !this.key_comp()(x, y) && !this.key_comp()(y, x); + } + + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public emplace(key: Key, val: T): IteratorT { - // FIND POSITION TO INSERT - let it: IteratorT = this.upper_bound(key); - - // ITERATOR TO RETURN - it = this.data_.insert(it, new Entry(key, val)); - this._Handle_insert(it, it.next()); - - return it; - } - - /** - * @inheritDoc - */ - public emplace_hint(hint: IteratorT, key: Key, val: T): IteratorT { - const elem: Entry = new Entry(key, val); - const validate: boolean = ITreeContainer.emplacable< - Key, - Entry, - Source, - IteratorT, - ReverseT, - IPair - >(this as Temporary, hint, elem); - - if (validate) { - const it: IteratorT = this.data_.insert(hint, elem); - this._Handle_insert(it, it.next()); - - return it; - } else return this.emplace(key, val); - } - - protected _Insert_by_range< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - >(first: InputIterator, last: InputIterator): void { - for (let it = first; !it.equals(last); it = it.next()) - this.emplace(it.value.first, it.value.second); - } + /** + * @inheritDoc + */ + public emplace(key: Key, val: T): IteratorT { + // FIND POSITION TO INSERT + let it: IteratorT = this.upper_bound(key); + + // ITERATOR TO RETURN + it = this.data_.insert(it, new Entry(key, val)); + this._Handle_insert(it, it.next()); + + return it; + } + + /** + * @inheritDoc + */ + public emplace_hint(hint: IteratorT, key: Key, val: T): IteratorT { + const elem: Entry = new Entry(key, val); + const validate: boolean = ITreeContainer.emplacable< + Key, + Entry, + Source, + IteratorT, + ReverseT, + IPair + >(this as Temporary, hint, elem); + + if (validate) { + const it: IteratorT = this.data_.insert(hint, elem); + this._Handle_insert(it, it.next()); + + return it; + } else return this.emplace(key, val); + } + + protected _Insert_by_range< + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + >(first: InputIterator, last: InputIterator): void { + for (let it = first; !it.equals(last); it = it.next()) + this.emplace(it.value.first, it.value.second); + } } diff --git a/src/internal/container/associative/MultiTreeSet.ts b/src/internal/container/associative/MultiTreeSet.ts index 1a051901..20c2d1cd 100644 --- a/src/internal/container/associative/MultiTreeSet.ts +++ b/src/internal/container/associative/MultiTreeSet.ts @@ -1,17 +1,16 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ import { MultiSet } from "../../../base/container/MultiSet"; -import { ITreeContainer } from "./ITreeContainer"; - import { IForwardIterator } from "../../../iterator/IForwardIterator"; import { Pair } from "../../../utility/Pair"; - import { Comparator } from "../../functional/Comparator"; import { Temporary } from "../../functional/Temporary"; +import { ITreeContainer } from "./ITreeContainer"; /** * Basic tree set allowing duplicated keys. @@ -25,117 +24,112 @@ import { Temporary } from "../../functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class MultiTreeSet< - Key, - Source extends MultiTreeSet, - IteratorT extends MultiSet.Iterator, - ReverseT extends MultiSet.ReverseIterator< - Key, - Source, - IteratorT, - ReverseT - >, - > - extends MultiSet - implements ITreeContainer + Key, + Source extends MultiTreeSet, + IteratorT extends MultiSet.Iterator, + ReverseT extends MultiSet.ReverseIterator, + > + extends MultiSet + implements ITreeContainer { - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public find(key: Key): IteratorT { - const it: IteratorT = this.lower_bound(key); - if (!it.equals(this.end()) && this._Key_eq(key, it.value)) return it; - else return this.end(); - } - - /** - * @inheritDoc - */ - public count(key: Key): number { - let it: IteratorT = this.find(key); - let ret: number = 0; - - for ( - ; - !it.equals(this.end()) && this._Key_eq(it.value, key); - it = it.next() - ) - ++ret; - - return ret; - } - - /** - * @inheritDoc - */ - public abstract lower_bound(key: Key): IteratorT; - - /** - * @inheritDoc - */ - public abstract upper_bound(key: Key): IteratorT; - - /** - * @inheritDoc - */ - public equal_range(key: Key): Pair { - return new Pair(this.lower_bound(key), this.upper_bound(key)); - } - - /** - * @inheritDoc - */ - public abstract key_comp(): Comparator; - - /** - * @inheritDoc - */ - public value_comp(): Comparator { - return this.key_comp(); - } - - protected _Key_eq(x: Key, y: Key): boolean { - return !this.key_comp()(x, y) && !this.key_comp()(y, x); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public find(key: Key): IteratorT { + const it: IteratorT = this.lower_bound(key); + if (!it.equals(this.end()) && this._Key_eq(key, it.value)) return it; + else return this.end(); + } + + /** + * @inheritDoc + */ + public count(key: Key): number { + let it: IteratorT = this.find(key); + let ret: number = 0; + + for ( + ; + !it.equals(this.end()) && this._Key_eq(it.value, key); + it = it.next() + ) + ++ret; + + return ret; + } + + /** + * @inheritDoc + */ + public abstract lower_bound(key: Key): IteratorT; + + /** + * @inheritDoc + */ + public abstract upper_bound(key: Key): IteratorT; + + /** + * @inheritDoc + */ + public equal_range(key: Key): Pair { + return new Pair(this.lower_bound(key), this.upper_bound(key)); + } + + /** + * @inheritDoc + */ + public abstract key_comp(): Comparator; + + /** + * @inheritDoc + */ + public value_comp(): Comparator { + return this.key_comp(); + } + + protected _Key_eq(x: Key, y: Key): boolean { + return !this.key_comp()(x, y) && !this.key_comp()(y, x); + } + + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - protected _Insert_by_key(key: Key): IteratorT { - // FIND POSITION TO INSERT - let it: IteratorT = this.upper_bound(key); - - // ITERATOR TO RETURN - it = this.data_.insert(it, key); - this._Handle_insert(it, it.next()); - - return it; - } - - protected _Insert_by_hint(hint: IteratorT, key: Key): IteratorT { - const validate: boolean = ITreeContainer.emplacable< - Key, - Key, - Source, - IteratorT, - ReverseT, - Key - >(this as Temporary, hint, key); - - if (validate) { - const it: IteratorT = this.data_.insert(hint, key); - this._Handle_insert(it, it.next()); - - return it; - } else return this._Insert_by_key(key); - } - - protected _Insert_by_range< - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void { - for (let it = first; !it.equals(last); it = it.next()) - this._Insert_by_key(it.value); - } + protected _Insert_by_key(key: Key): IteratorT { + // FIND POSITION TO INSERT + let it: IteratorT = this.upper_bound(key); + + // ITERATOR TO RETURN + it = this.data_.insert(it, key); + this._Handle_insert(it, it.next()); + + return it; + } + + protected _Insert_by_hint(hint: IteratorT, key: Key): IteratorT { + const validate: boolean = ITreeContainer.emplacable< + Key, + Key, + Source, + IteratorT, + ReverseT, + Key + >(this as Temporary, hint, key); + + if (validate) { + const it: IteratorT = this.data_.insert(hint, key); + this._Handle_insert(it, it.next()); + + return it; + } else return this._Insert_by_key(key); + } + + protected _Insert_by_range< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void { + for (let it = first; !it.equals(last); it = it.next()) + this._Insert_by_key(it.value); + } } diff --git a/src/internal/container/associative/SetElementList.ts b/src/internal/container/associative/SetElementList.ts index d546a9b8..69c6a39d 100644 --- a/src/internal/container/associative/SetElementList.ts +++ b/src/internal/container/associative/SetElementList.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { ListContainer } from "../linear/ListContainer"; +import { SetContainer } from "../../../base/container/SetContainer"; import { ListIterator } from "../../iterator/ListIterator"; import { ReverseIterator as _ReverseIterator } from "../../iterator/ReverseIterator"; - -import { SetContainer } from "../../../base/container/SetContainer"; +import { ListContainer } from "../linear/ListContainer"; /** * Doubly Linked List storing set elements. @@ -20,203 +20,203 @@ import { SetContainer } from "../../../base/container/SetContainer"; * @author Jeongho Nam - https://github.com/samchon */ export class SetElementList< + Key, + Unique extends boolean, + Source extends SetContainer< Key, - Unique extends boolean, - Source extends SetContainer< - Key, - Unique, - Source, - SetElementList.Iterator, - SetElementList.ReverseIterator - >, -> extends ListContainer< - Key, + Unique, Source, SetElementList.Iterator, SetElementList.ReverseIterator + >, +> extends ListContainer< + Key, + Source, + SetElementList.Iterator, + SetElementList.ReverseIterator > { - private associative_: Source; + private associative_: Source; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - public constructor(associative: Source) { - super(); + public constructor(associative: Source) { + super(); - this.associative_ = associative; - } + this.associative_ = associative; + } - protected _Create_iterator( - prev: SetElementList.Iterator, - next: SetElementList.Iterator, - val: Key, - ): SetElementList.Iterator { - return SetElementList.Iterator.create(this, prev, next, val); - } + protected _Create_iterator( + prev: SetElementList.Iterator, + next: SetElementList.Iterator, + val: Key, + ): SetElementList.Iterator { + return SetElementList.Iterator.create(this, prev, next, val); + } - /** - * @internal - */ - public static _Swap_associative< - Key, - Unique extends boolean, - Source extends SetContainer< - Key, - Unique, - Source, - SetElementList.Iterator, - SetElementList.ReverseIterator - >, - >( - x: SetElementList, - y: SetElementList, - ): void { - [x.associative_, y.associative_] = [y.associative_, x.associative_]; - } + /** + * @internal + */ + public static _Swap_associative< + Key, + Unique extends boolean, + Source extends SetContainer< + Key, + Unique, + Source, + SetElementList.Iterator, + SetElementList.ReverseIterator + >, + >( + x: SetElementList, + y: SetElementList, + ): void { + [x.associative_, y.associative_] = [y.associative_, x.associative_]; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - public associative(): Source { - return this.associative_; - } + public associative(): Source { + return this.associative_; + } } /** * */ export namespace SetElementList { - /** - * Iterator of set container storing elements in a list. - * - * @template Key Key type - * @template Unique Whether duplicated key is blocked or not - * @template Source Source container type - * - * @author Jeongho Nam - https://github.com/samchon - */ - export class Iterator< - Key, - Unique extends boolean, - Source extends SetContainer< - Key, - Unique, - Source, - Iterator, - ReverseIterator - >, - > - extends ListIterator< - Key, - Source, - Iterator, - ReverseIterator, - Key - > - implements - SetContainer.Iterator< - Key, - Unique, - Source, - Iterator, - ReverseIterator - > - { - private source_: SetElementList; + /** + * Iterator of set container storing elements in a list. + * + * @template Key Key type + * @template Unique Whether duplicated key is blocked or not + * @template Source Source container type + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class Iterator< + Key, + Unique extends boolean, + Source extends SetContainer< + Key, + Unique, + Source, + Iterator, + ReverseIterator + >, + > + extends ListIterator< + Key, + Source, + Iterator, + ReverseIterator, + Key + > + implements + SetContainer.Iterator< + Key, + Unique, + Source, + Iterator, + ReverseIterator + > + { + private source_: SetElementList; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - private constructor( - list: SetElementList, - prev: Iterator, - next: Iterator, - val: Key, - ) { - super(prev, next, val); - this.source_ = list; - } + private constructor( + list: SetElementList, + prev: Iterator, + next: Iterator, + val: Key, + ) { + super(prev, next, val); + this.source_ = list; + } - /** - * @internal - */ - public static create< - Key, - Unique extends boolean, - Source extends SetContainer< - Key, - Unique, - Source, - Iterator, - ReverseIterator - >, - >( - list: SetElementList, - prev: Iterator, - next: Iterator, - val: Key, - ) { - return new Iterator(list, prev, next, val); - } + /** + * @internal + */ + public static create< + Key, + Unique extends boolean, + Source extends SetContainer< + Key, + Unique, + Source, + Iterator, + ReverseIterator + >, + >( + list: SetElementList, + prev: Iterator, + next: Iterator, + val: Key, + ) { + return new Iterator(list, prev, next, val); + } - /** - * @inheritDoc - */ - public reverse(): ReverseIterator { - return new ReverseIterator(this); - } + /** + * @inheritDoc + */ + public reverse(): ReverseIterator { + return new ReverseIterator(this); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public source(): Source { - return this.source_.associative(); - } - } - /** - * Reverser iterator of set container storing elements in a list. - * - * @template Key Key type - * @template Unique Whether duplicated key is blocked or not - * @template Source Source container type - * - * @author Jeongho Nam - https://github.com/samchon + * @inheritDoc */ - export class ReverseIterator< - Key, - Unique extends boolean, - Source extends SetContainer< - Key, - Unique, - Source, - Iterator, - ReverseIterator - >, - > - extends _ReverseIterator< - Key, - Source, - Iterator, - ReverseIterator, - Key - > - implements - SetContainer.ReverseIterator< - Key, - Unique, - Source, - Iterator, - ReverseIterator - > - { - protected _Create_neighbor( - base: Iterator, - ): ReverseIterator { - return new ReverseIterator(base); - } + public source(): Source { + return this.source_.associative(); + } + } + + /** + * Reverser iterator of set container storing elements in a list. + * + * @template Key Key type + * @template Unique Whether duplicated key is blocked or not + * @template Source Source container type + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class ReverseIterator< + Key, + Unique extends boolean, + Source extends SetContainer< + Key, + Unique, + Source, + Iterator, + ReverseIterator + >, + > + extends _ReverseIterator< + Key, + Source, + Iterator, + ReverseIterator, + Key + > + implements + SetContainer.ReverseIterator< + Key, + Unique, + Source, + Iterator, + ReverseIterator + > + { + protected _Create_neighbor( + base: Iterator, + ): ReverseIterator { + return new ReverseIterator(base); } + } } diff --git a/src/internal/container/associative/SetElementVector.ts b/src/internal/container/associative/SetElementVector.ts index c1be4ca4..685e8cb1 100644 --- a/src/internal/container/associative/SetElementVector.ts +++ b/src/internal/container/associative/SetElementVector.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { VectorContainer } from "../linear/VectorContainer"; +import { ITreeSet } from "../../../base/container/ITreeSet"; import { ArrayIteratorBase } from "../../iterator/ArrayIteratorBase"; import { ArrayReverseIteratorBase } from "../../iterator/ArrayReverseIteratorBase"; - -import { ITreeSet } from "../../../base/container/ITreeSet"; +import { VectorContainer } from "../linear/VectorContainer"; /** * Vector storing set elements. @@ -20,163 +20,163 @@ import { ITreeSet } from "../../../base/container/ITreeSet"; * @author Jeongho Nam - https://github.com/samchon */ export class SetElementVector< + Key, + Unique extends boolean, + Source extends ITreeSet< Key, - Unique extends boolean, - Source extends ITreeSet< - Key, - Unique, - Source, - SetElementVector.Iterator, - SetElementVector.ReverseIterator - >, -> extends VectorContainer< - Key, + Unique, Source, - SetElementVector, SetElementVector.Iterator, SetElementVector.ReverseIterator + >, +> extends VectorContainer< + Key, + Source, + SetElementVector, + SetElementVector.Iterator, + SetElementVector.ReverseIterator > { - private associative_: Source; + private associative_: Source; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - public constructor(associative: Source) { - super(); + public constructor(associative: Source) { + super(); - this.data_ = []; - this.associative_ = associative; - } + this.data_ = []; + this.associative_ = associative; + } - public nth(index: number): SetElementVector.Iterator { - return new SetElementVector.Iterator(this, index); - } + public nth(index: number): SetElementVector.Iterator { + return new SetElementVector.Iterator(this, index); + } - /** - * @internal - */ - public static _Swap_associative< - Key, - Unique extends boolean, - Source extends ITreeSet< - Key, - Unique, - Source, - SetElementVector.Iterator, - SetElementVector.ReverseIterator - >, - >( - x: SetElementVector, - y: SetElementVector, - ): void { - [x.associative_, y.associative_] = [y.associative_, x.associative_]; - } + /** + * @internal + */ + public static _Swap_associative< + Key, + Unique extends boolean, + Source extends ITreeSet< + Key, + Unique, + Source, + SetElementVector.Iterator, + SetElementVector.ReverseIterator + >, + >( + x: SetElementVector, + y: SetElementVector, + ): void { + [x.associative_, y.associative_] = [y.associative_, x.associative_]; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - public source(): Source { - return this.associative_; - } + public source(): Source { + return this.associative_; + } } /** * */ export namespace SetElementVector { + /** + * Iterator of set container storing elements in a vector. + * + * @template Key Key type + * @template Unique Whether duplicated key is blocked or not + * @template Source Source container type + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class Iterator< + Key, + Unique extends boolean, + Source extends ITreeSet< + Key, + Unique, + Source, + SetElementVector.Iterator, + SetElementVector.ReverseIterator + >, + > + extends ArrayIteratorBase< + Key, + Source, + SetElementVector, + SetElementVector.Iterator, + SetElementVector.ReverseIterator, + Key + > + implements + ITreeSet.Iterator< + Key, + Unique, + Source, + SetElementVector.Iterator, + SetElementVector.ReverseIterator + > + { /** - * Iterator of set container storing elements in a vector. - * - * @template Key Key type - * @template Unique Whether duplicated key is blocked or not - * @template Source Source container type - * - * @author Jeongho Nam - https://github.com/samchon + * @inheritDoc */ - export class Iterator< - Key, - Unique extends boolean, - Source extends ITreeSet< - Key, - Unique, - Source, - SetElementVector.Iterator, - SetElementVector.ReverseIterator - >, - > - extends ArrayIteratorBase< - Key, - Source, - SetElementVector, - SetElementVector.Iterator, - SetElementVector.ReverseIterator, - Key - > - implements - ITreeSet.Iterator< - Key, - Unique, - Source, - SetElementVector.Iterator, - SetElementVector.ReverseIterator - > - { - /** - * @inheritDoc - */ - public source(): Source { - return this._Get_array().source(); - } - - /** - * @inheritDoc - */ - public reverse(): ReverseIterator { - return new ReverseIterator(this); - } + public source(): Source { + return this._Get_array().source(); } /** - * Reverse iterator of set container storing elements in a vector. - * - * @template Key Key type - * @template Unique Whether duplicated key is blocked or not - * @template Source Source container type - * - * @author Jeongho Nam - https://github.com/samchon + * @inheritDoc */ - export class ReverseIterator< - Key, - Unique extends boolean, - Source extends ITreeSet< - Key, - Unique, - Source, - SetElementVector.Iterator, - SetElementVector.ReverseIterator - >, - > - extends ArrayReverseIteratorBase< - Key, - Source, - SetElementVector, - SetElementVector.Iterator, - SetElementVector.ReverseIterator, - Key - > - implements - ITreeSet.ReverseIterator< - Key, - Unique, - Source, - SetElementVector.Iterator, - SetElementVector.ReverseIterator - > - { - protected _Create_neighbor( - base: Iterator, - ): ReverseIterator { - return new ReverseIterator(base); - } + public reverse(): ReverseIterator { + return new ReverseIterator(this); + } + } + + /** + * Reverse iterator of set container storing elements in a vector. + * + * @template Key Key type + * @template Unique Whether duplicated key is blocked or not + * @template Source Source container type + * + * @author Jeongho Nam - https://github.com/samchon + */ + export class ReverseIterator< + Key, + Unique extends boolean, + Source extends ITreeSet< + Key, + Unique, + Source, + SetElementVector.Iterator, + SetElementVector.ReverseIterator + >, + > + extends ArrayReverseIteratorBase< + Key, + Source, + SetElementVector, + SetElementVector.Iterator, + SetElementVector.ReverseIterator, + Key + > + implements + ITreeSet.ReverseIterator< + Key, + Unique, + Source, + SetElementVector.Iterator, + SetElementVector.ReverseIterator + > + { + protected _Create_neighbor( + base: Iterator, + ): ReverseIterator { + return new ReverseIterator(base); } + } } diff --git a/src/internal/container/associative/UniqueTreeMap.ts b/src/internal/container/associative/UniqueTreeMap.ts index 2cafa93f..48fb22d3 100644 --- a/src/internal/container/associative/UniqueTreeMap.ts +++ b/src/internal/container/associative/UniqueTreeMap.ts @@ -1,18 +1,17 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ import { UniqueMap } from "../../../base/container/UniqueMap"; -import { ITreeContainer } from "./ITreeContainer"; - -import { IPair } from "../../../utility/IPair"; import { Entry } from "../../../utility/Entry"; +import { IPair } from "../../../utility/IPair"; import { Pair } from "../../../utility/Pair"; - import { Comparator } from "../../functional/Comparator"; import { Temporary } from "../../functional/Temporary"; +import { ITreeContainer } from "./ITreeContainer"; /** * Basic tree map blocking duplicated key. @@ -26,124 +25,116 @@ import { Temporary } from "../../functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class UniqueTreeMap< - Key, - T, - Source extends UniqueTreeMap, - IteratorT extends UniqueMap.Iterator< - Key, - T, - Source, - IteratorT, - ReverseT - >, - ReverseT extends UniqueMap.ReverseIterator< - Key, - T, - Source, - IteratorT, - ReverseT - >, + Key, + T, + Source extends UniqueTreeMap, + IteratorT extends UniqueMap.Iterator, + ReverseT extends UniqueMap.ReverseIterator< + Key, + T, + Source, + IteratorT, + ReverseT + >, + > + extends UniqueMap + implements + ITreeContainer< + Key, + Entry, + Source, + IteratorT, + ReverseT, + IPair > - extends UniqueMap - implements - ITreeContainer< - Key, - Entry, - Source, - IteratorT, - ReverseT, - IPair - > { - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public find(key: Key): IteratorT { - const it: IteratorT = this.lower_bound(key); - if (!it.equals(this.end()) && this._Key_eq(key, it.first)) return it; - else return this.end(); - } + /** + * @inheritDoc + */ + public find(key: Key): IteratorT { + const it: IteratorT = this.lower_bound(key); + if (!it.equals(this.end()) && this._Key_eq(key, it.first)) return it; + else return this.end(); + } - /** - * @inheritDoc - */ - public abstract lower_bound(key: Key): IteratorT; + /** + * @inheritDoc + */ + public abstract lower_bound(key: Key): IteratorT; - /** - * @inheritDoc - */ - public abstract upper_bound(key: Key): IteratorT; + /** + * @inheritDoc + */ + public abstract upper_bound(key: Key): IteratorT; - /** - * @inheritDoc - */ - public equal_range(key: Key): Pair { - const it: IteratorT = this.lower_bound(key); - return new Pair( - it, - !it.equals(this.end()) && this._Key_eq(key, it.first) - ? it.next() - : it, - ); - } + /** + * @inheritDoc + */ + public equal_range(key: Key): Pair { + const it: IteratorT = this.lower_bound(key); + return new Pair( + it, + !it.equals(this.end()) && this._Key_eq(key, it.first) ? it.next() : it, + ); + } - /** - * @inheritDoc - */ - public abstract key_comp(): Comparator; + /** + * @inheritDoc + */ + public abstract key_comp(): Comparator; - /** - * @inheritDoc - */ - public value_comp(): Comparator> { - return (x, y) => this.key_comp()(x.first, y.first); - } + /** + * @inheritDoc + */ + public value_comp(): Comparator> { + return (x, y) => this.key_comp()(x.first, y.first); + } - protected _Key_eq(x: Key, y: Key): boolean { - return !this.key_comp()(x, y) && !this.key_comp()(y, x); - } + protected _Key_eq(x: Key, y: Key): boolean { + return !this.key_comp()(x, y) && !this.key_comp()(y, x); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public emplace(key: Key, val: T): Pair { - // FIND POSITION TO INSERT - let it: IteratorT = this.lower_bound(key); - if (!it.equals(this.end()) && this._Key_eq(it.first, key)) - return new Pair(it, false); + /** + * @inheritDoc + */ + public emplace(key: Key, val: T): Pair { + // FIND POSITION TO INSERT + let it: IteratorT = this.lower_bound(key); + if (!it.equals(this.end()) && this._Key_eq(it.first, key)) + return new Pair(it, false); - // ITERATOR TO RETURN - it = this.data_.insert(it, new Entry(key, val)); - this._Handle_insert(it, it.next()); + // ITERATOR TO RETURN + it = this.data_.insert(it, new Entry(key, val)); + this._Handle_insert(it, it.next()); - return new Pair(it, true); - } + return new Pair(it, true); + } - /** - * @inheritDoc - */ - public emplace_hint(hint: IteratorT, key: Key, val: T): IteratorT { - const elem: Entry = new Entry(key, val); - const validate: boolean = ITreeContainer.emplacable< - Key, - Entry, - Source, - IteratorT, - ReverseT, - IPair - >(this as Temporary, hint, elem); + /** + * @inheritDoc + */ + public emplace_hint(hint: IteratorT, key: Key, val: T): IteratorT { + const elem: Entry = new Entry(key, val); + const validate: boolean = ITreeContainer.emplacable< + Key, + Entry, + Source, + IteratorT, + ReverseT, + IPair + >(this as Temporary, hint, elem); - if (validate) { - const it: IteratorT = this.data_.insert(hint, elem); - this._Handle_insert(it, it.next()); + if (validate) { + const it: IteratorT = this.data_.insert(hint, elem); + this._Handle_insert(it, it.next()); - return it; - } else return this.emplace(key, val).first; - } + return it; + } else return this.emplace(key, val).first; + } } diff --git a/src/internal/container/associative/UniqueTreeSet.ts b/src/internal/container/associative/UniqueTreeSet.ts index 112c949a..8866e838 100644 --- a/src/internal/container/associative/UniqueTreeSet.ts +++ b/src/internal/container/associative/UniqueTreeSet.ts @@ -1,16 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ import { UniqueSet } from "../../../base/container/UniqueSet"; -import { ITreeContainer } from "./ITreeContainer"; - import { Pair } from "../../../utility/Pair"; - import { Comparator } from "../../functional/Comparator"; import { Temporary } from "../../functional/Temporary"; +import { ITreeContainer } from "./ITreeContainer"; /** * Basic tree set blocking duplicated key. @@ -23,101 +22,99 @@ import { Temporary } from "../../functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class UniqueTreeSet< - Key, - Source extends UniqueTreeSet, - IteratorT extends UniqueSet.Iterator, - ReverseT extends UniqueSet.ReverseIterator< - Key, - Source, - IteratorT, - ReverseT - >, - > - extends UniqueSet - implements ITreeContainer + Key, + Source extends UniqueTreeSet, + IteratorT extends UniqueSet.Iterator, + ReverseT extends UniqueSet.ReverseIterator< + Key, + Source, + IteratorT, + ReverseT + >, + > + extends UniqueSet + implements ITreeContainer { - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public find(key: Key): IteratorT { - const it: IteratorT = this.lower_bound(key); - if (!it.equals(this.end()) && this._Key_eq(key, it.value)) return it; - else return this.end(); - } + /** + * @inheritDoc + */ + public find(key: Key): IteratorT { + const it: IteratorT = this.lower_bound(key); + if (!it.equals(this.end()) && this._Key_eq(key, it.value)) return it; + else return this.end(); + } - /** - * @inheritDoc - */ - public abstract lower_bound(key: Key): IteratorT; + /** + * @inheritDoc + */ + public abstract lower_bound(key: Key): IteratorT; - /** - * @inheritDoc - */ - public abstract upper_bound(key: Key): IteratorT; + /** + * @inheritDoc + */ + public abstract upper_bound(key: Key): IteratorT; - /** - * @inheritDoc - */ - public equal_range(key: Key): Pair { - const it: IteratorT = this.lower_bound(key); - return new Pair( - it, - !it.equals(this.end()) && this._Key_eq(key, it.value) - ? it.next() - : it, - ); - } + /** + * @inheritDoc + */ + public equal_range(key: Key): Pair { + const it: IteratorT = this.lower_bound(key); + return new Pair( + it, + !it.equals(this.end()) && this._Key_eq(key, it.value) ? it.next() : it, + ); + } - /** - * @inheritDoc - */ - public abstract key_comp(): Comparator; + /** + * @inheritDoc + */ + public abstract key_comp(): Comparator; - /** - * @inheritDoc - */ - public value_comp(): Comparator { - return this.key_comp(); - } + /** + * @inheritDoc + */ + public value_comp(): Comparator { + return this.key_comp(); + } - protected _Key_eq(x: Key, y: Key): boolean { - return !this.key_comp()(x, y) && !this.key_comp()(y, x); - } + protected _Key_eq(x: Key, y: Key): boolean { + return !this.key_comp()(x, y) && !this.key_comp()(y, x); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - protected _Insert_by_key(key: Key): Pair { - // FIND POSITION TO INSERT - let it: IteratorT = this.lower_bound(key); - if (!it.equals(this.end()) && this._Key_eq(it.value, key)) - return new Pair(it, false); + protected _Insert_by_key(key: Key): Pair { + // FIND POSITION TO INSERT + let it: IteratorT = this.lower_bound(key); + if (!it.equals(this.end()) && this._Key_eq(it.value, key)) + return new Pair(it, false); - // ITERATOR TO RETURN - it = this.data_.insert(it, key); - this._Handle_insert(it, it.next()); + // ITERATOR TO RETURN + it = this.data_.insert(it, key); + this._Handle_insert(it, it.next()); - return new Pair(it, true); - } + return new Pair(it, true); + } - protected _Insert_by_hint(hint: IteratorT, key: Key): IteratorT { - const validate: boolean = ITreeContainer.emplacable< - Key, - Key, - Source, - IteratorT, - ReverseT, - Key - >(this as Temporary, hint, key); + protected _Insert_by_hint(hint: IteratorT, key: Key): IteratorT { + const validate: boolean = ITreeContainer.emplacable< + Key, + Key, + Source, + IteratorT, + ReverseT, + Key + >(this as Temporary, hint, key); - if (validate) { - const it: IteratorT = this.data_.insert(hint, key); - this._Handle_insert(it, it.next()); + if (validate) { + const it: IteratorT = this.data_.insert(hint, key); + this._Handle_insert(it, it.next()); - return it; - } else return this._Insert_by_key(key).first; - } + return it; + } else return this._Insert_by_key(key).first; + } } diff --git a/src/internal/container/linear/AdaptorContainer.ts b/src/internal/container/linear/AdaptorContainer.ts index 34795218..84a8e438 100644 --- a/src/internal/container/linear/AdaptorContainer.ts +++ b/src/internal/container/linear/AdaptorContainer.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -14,55 +15,55 @@ import { ISize } from "../partial/ISize"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class AdaptorContainer< - T, - Source extends IEmpty & ISize & IPush, - This extends AdaptorContainer, + T, + Source extends IEmpty & ISize & IPush, + This extends AdaptorContainer, > implements IEmpty, ISize, IPush { - protected source_: Source; + protected source_: Source; - protected constructor(source: Source) { - this.source_ = source; - } + protected constructor(source: Source) { + this.source_ = source; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public size(): number { - return this.source_.size(); - } + /** + * @inheritDoc + */ + public size(): number { + return this.source_.size(); + } - /** - * @inheritDoc - */ - public empty(): boolean { - return this.source_.empty(); - } + /** + * @inheritDoc + */ + public empty(): boolean { + return this.source_.empty(); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ELEMENTS I/O --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public push(...elems: T[]): number { - return this.source_.push(...elems); - } + /** + * @inheritDoc + */ + public push(...elems: T[]): number { + return this.source_.push(...elems); + } - /** - * Remove element. - */ - public abstract pop(): void; + /** + * Remove element. + */ + public abstract pop(): void; - /** - * Swap elements. - * - * @param obj Target container to swap. - */ - public swap(obj: This): void { - [this.source_, obj.source_] = [obj.source_, this.source_]; - } + /** + * Swap elements. + * + * @param obj Target container to swap. + */ + public swap(obj: This): void { + [this.source_, obj.source_] = [obj.source_, this.source_]; + } } diff --git a/src/internal/container/linear/ArrayContainer.ts b/src/internal/container/linear/ArrayContainer.ts index 8b6460bb..b71720ea 100644 --- a/src/internal/container/linear/ArrayContainer.ts +++ b/src/internal/container/linear/ArrayContainer.ts @@ -1,20 +1,19 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { ILinearContainerBase } from "./ILinearContainerBase"; import { Container } from "../../../base/container/Container"; - import { IContainer } from "../../../base/container/IContainer"; +import { RangeError } from "../../../exception/RangeError"; import { IForwardIterator } from "../../../iterator/IForwardIterator"; +import { ErrorGenerator } from "../../exception/ErrorGenerator"; import { ArrayIteratorBase } from "../../iterator/ArrayIteratorBase"; import { ArrayReverseIteratorBase } from "../../iterator/ArrayReverseIteratorBase"; - -import { ErrorGenerator } from "../../exception/ErrorGenerator"; -import { RangeError } from "../../../exception/RangeError"; import { Repeater } from "../../iterator/disposable/Repeater"; +import { ILinearContainerBase } from "./ILinearContainerBase"; /** * Base array container. @@ -22,137 +21,137 @@ import { Repeater } from "../../iterator/disposable/Repeater"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class ArrayContainer< - T extends ElemT, - SourceT extends IContainer, - ArrayT extends ArrayContainer< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - ElemT - >, - IteratorT extends ArrayIteratorBase< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - ElemT - >, - ReverseT extends ArrayReverseIteratorBase< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - ElemT - >, - ElemT, - > - extends Container - implements ILinearContainerBase + T extends ElemT, + SourceT extends IContainer, + ArrayT extends ArrayContainer< + T, + SourceT, + ArrayT, + IteratorT, + ReverseT, + ElemT + >, + IteratorT extends ArrayIteratorBase< + T, + SourceT, + ArrayT, + IteratorT, + ReverseT, + ElemT + >, + ReverseT extends ArrayReverseIteratorBase< + T, + SourceT, + ArrayT, + IteratorT, + ReverseT, + ElemT + >, + ElemT, + > + extends Container + implements ILinearContainerBase { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract resize(n: number): void; + /** + * @inheritDoc + */ + public abstract resize(n: number): void; - protected abstract source(): SourceT; + protected abstract source(): SourceT; - /* ========================================================= + /* ========================================================= ACCESSORS - ITERATORS - INDEXES ============================================================ ITERATORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public begin(): IteratorT { - return this.nth(0); - } - - /** - * @inheritDoc - */ - public end(): IteratorT { - return this.nth(this.size()); - } - - public abstract nth(index: number): IteratorT; - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public begin(): IteratorT { + return this.nth(0); + } + + /** + * @inheritDoc + */ + public end(): IteratorT { + return this.nth(this.size()); + } + + public abstract nth(index: number): IteratorT; + + /* --------------------------------------------------------- INDEXES --------------------------------------------------------- */ - /** - * Get element at specific position. - * - * @param index Specific position. - * @return The element at the *index*. - */ - public at(index: number): T { - return this._At(index); - } - protected abstract _At(index: number): T; - - /** - * Change element at specific position. - * - * @param index Specific position. - * @param val The new value to change. - */ - public set(index: number, val: T): void { - if (index < 0) - throw ErrorGenerator.negative_index(this.source(), "at", index); - else if (index >= this.size()) - throw ErrorGenerator.excessive_index( - this.source(), - "at", - index, - this.size(), - ); - - this._Set(index, val); - } - protected abstract _Set(index: number, val: T): void; - - /** - * @inheritDoc - */ - public front(): T; - - /** - * @inheritDoc - */ - public front(val: T): void; - - public front(val?: T): T | void { - if (arguments.length === 0) return this.at(0); - else this.set(0, val!); - } - - /** - * @inheritDoc - */ - public back(): T; - - /** - * @inheritDoc - */ - public back(val: T): void; - - public back(val?: T): T | void { - const index: number = this.size() - 1; - if (arguments.length === 0) return this.at(index); - else this.set(index, val!); - } - - /* ========================================================= + /** + * Get element at specific position. + * + * @param index Specific position. + * @return The element at the *index*. + */ + public at(index: number): T { + return this._At(index); + } + protected abstract _At(index: number): T; + + /** + * Change element at specific position. + * + * @param index Specific position. + * @param val The new value to change. + */ + public set(index: number, val: T): void { + if (index < 0) + throw ErrorGenerator.negative_index(this.source(), "at", index); + else if (index >= this.size()) + throw ErrorGenerator.excessive_index( + this.source(), + "at", + index, + this.size(), + ); + + this._Set(index, val); + } + protected abstract _Set(index: number, val: T): void; + + /** + * @inheritDoc + */ + public front(): T; + + /** + * @inheritDoc + */ + public front(val: T): void; + + public front(val?: T): T | void { + if (arguments.length === 0) return this.at(0); + else this.set(0, val!); + } + + /** + * @inheritDoc + */ + public back(): T; + + /** + * @inheritDoc + */ + public back(val: T): void; + + public back(val?: T): T | void { + const index: number = this.size() - 1; + if (arguments.length === 0) return this.at(index); + else this.set(index, val!); + } + + /* ========================================================= ELEMENTS I/O - INSERT - ERASE @@ -160,113 +159,113 @@ export abstract class ArrayContainer< ============================================================ INSERT --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract push_back(val: T): void; - - /** - * @inheritDoc - */ - public insert(pos: IteratorT, val: T): IteratorT; - - /** - * @inheritDoc - */ - public insert(pos: IteratorT, n: number, val: T): IteratorT; - - /** - * @inheritDoc - */ - public insert< - InputIterator extends Readonly>, - >(pos: IteratorT, first: InputIterator, last: InputIterator): IteratorT; - - public insert(pos: IteratorT, ...args: any[]): IteratorT { - // VALIDATION - if (pos._Get_array() !== this) - throw ErrorGenerator.not_my_iterator(this.source(), "insert"); - else if (pos.index() < 0) - throw ErrorGenerator.negative_iterator( - this.source(), - "insert", - pos.index(), - ); - else if (pos.index() > this.size()) pos = this.end(); - - // BRANCHES - if (args.length === 1) - return this._Insert_by_repeating_val(pos, 1, args[0]); - else if (args.length === 2 && typeof args[0] === "number") - return this._Insert_by_repeating_val(pos, args[0], args[1]); - else return this._Insert_by_range(pos, args[0], args[1]); - } - - protected _Insert_by_repeating_val( - position: IteratorT, - n: number, - val: T, - ): IteratorT { - const first: Repeater = new Repeater(0, val); - const last: Repeater = new Repeater(n); - - return this._Insert_by_range(position, first, last); - } - - protected abstract _Insert_by_range< - InputIterator extends Readonly>, - >(pos: IteratorT, first: InputIterator, last: InputIterator): IteratorT; - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public abstract push_back(val: T): void; + + /** + * @inheritDoc + */ + public insert(pos: IteratorT, val: T): IteratorT; + + /** + * @inheritDoc + */ + public insert(pos: IteratorT, n: number, val: T): IteratorT; + + /** + * @inheritDoc + */ + public insert< + InputIterator extends Readonly>, + >(pos: IteratorT, first: InputIterator, last: InputIterator): IteratorT; + + public insert(pos: IteratorT, ...args: any[]): IteratorT { + // VALIDATION + if (pos._Get_array() !== this) + throw ErrorGenerator.not_my_iterator(this.source(), "insert"); + else if (pos.index() < 0) + throw ErrorGenerator.negative_iterator( + this.source(), + "insert", + pos.index(), + ); + else if (pos.index() > this.size()) pos = this.end(); + + // BRANCHES + if (args.length === 1) + return this._Insert_by_repeating_val(pos, 1, args[0]); + else if (args.length === 2 && typeof args[0] === "number") + return this._Insert_by_repeating_val(pos, args[0], args[1]); + else return this._Insert_by_range(pos, args[0], args[1]); + } + + protected _Insert_by_repeating_val( + position: IteratorT, + n: number, + val: T, + ): IteratorT { + const first: Repeater = new Repeater(0, val); + const last: Repeater = new Repeater(n); + + return this._Insert_by_range(position, first, last); + } + + protected abstract _Insert_by_range< + InputIterator extends Readonly>, + >(pos: IteratorT, first: InputIterator, last: InputIterator): IteratorT; + + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public pop_back(): void { - if (this.empty() === true) - throw ErrorGenerator.empty(this.source(), "pop_back"); - - this._Pop_back(); - } - protected abstract _Pop_back(): void; - - /** - * @inheritDoc - */ - public erase(it: IteratorT): IteratorT; - - /** - * @inheritDoc - */ - public erase(first: IteratorT, last: IteratorT): IteratorT; - - public erase(first: IteratorT, last: IteratorT = first.next()): IteratorT { - // VALIDATION - if (first._Get_array() !== this || last._Get_array() !== this) - throw ErrorGenerator.not_my_iterator(this.source(), "erase"); - else if (first.index() < 0) - throw ErrorGenerator.negative_iterator( - this.source(), - "erase", - first.index(), - ); - else if (first.index() > last.index()) - throw new RangeError( - `Error on ${ErrorGenerator.get_class_name( - this.source(), - )}.erase(): first iterator has greater index than last -> (first = ${first.index()}, last = ${last.index()}).`, - ); - - // ADJUSTMENT - if (first.index() >= this.size()) return this.end(); - - // ERASE ELEMENTS - return this._Erase_by_range(first, last); - } - - protected abstract _Erase_by_range( - first: IteratorT, - last: IteratorT, - ): IteratorT; + /** + * @inheritDoc + */ + public pop_back(): void { + if (this.empty() === true) + throw ErrorGenerator.empty(this.source(), "pop_back"); + + this._Pop_back(); + } + protected abstract _Pop_back(): void; + + /** + * @inheritDoc + */ + public erase(it: IteratorT): IteratorT; + + /** + * @inheritDoc + */ + public erase(first: IteratorT, last: IteratorT): IteratorT; + + public erase(first: IteratorT, last: IteratorT = first.next()): IteratorT { + // VALIDATION + if (first._Get_array() !== this || last._Get_array() !== this) + throw ErrorGenerator.not_my_iterator(this.source(), "erase"); + else if (first.index() < 0) + throw ErrorGenerator.negative_iterator( + this.source(), + "erase", + first.index(), + ); + else if (first.index() > last.index()) + throw new RangeError( + `Error on ${ErrorGenerator.get_class_name( + this.source(), + )}.erase(): first iterator has greater index than last -> (first = ${first.index()}, last = ${last.index()}).`, + ); + + // ADJUSTMENT + if (first.index() >= this.size()) return this.end(); + + // ERASE ELEMENTS + return this._Erase_by_range(first, last); + } + + protected abstract _Erase_by_range( + first: IteratorT, + last: IteratorT, + ): IteratorT; } diff --git a/src/internal/container/linear/ILinearContainerBase.ts b/src/internal/container/linear/ILinearContainerBase.ts index fe5a55fc..9db69339 100644 --- a/src/internal/container/linear/ILinearContainerBase.ts +++ b/src/internal/container/linear/ILinearContainerBase.ts @@ -1,100 +1,100 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ import { IContainer } from "../../../base/container/IContainer"; -import { IPushBack } from "../partial/IPushBack"; - import { IForwardIterator } from "../../../iterator/IForwardIterator"; +import { IPushBack } from "../partial/IPushBack"; export interface ILinearContainerBase< - T extends ElemT, - SourceT extends IContainer, - IteratorT extends IContainer.Iterator, - ReverseT extends IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT, - T - >, - ElemT = T, + T extends ElemT, + SourceT extends IContainer, + IteratorT extends IContainer.Iterator, + ReverseT extends IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT, + T + >, + ElemT = T, > extends IContainer, - IPushBack { - /* --------------------------------------------------------- + IPushBack { + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Fill Assigner. - * - * @param n Initial size. - * @param val Value to fill. - */ - assign(n: number, val: T): void; + /** + * Fill Assigner. + * + * @param n Initial size. + * @param val Value to fill. + */ + assign(n: number, val: T): void; - /** - * Range Assigner. - * - * @param first Input iterator of the first position. - * @param last Input iterator of the last position. - */ - assign>>( - first: InputIterator, - last: InputIterator, - ): void; + /** + * Range Assigner. + * + * @param first Input iterator of the first position. + * @param last Input iterator of the last position. + */ + assign>>( + first: InputIterator, + last: InputIterator, + ): void; - /** - * Resize this {@link Vector} forcibly. - * - * @param n New container size. - */ - resize(n: number): void; + /** + * Resize this {@link Vector} forcibly. + * + * @param n New container size. + */ + resize(n: number): void; - /* --------------------------------------------------------- + /* --------------------------------------------------------- ELEMENTS I/O --------------------------------------------------------- */ - /** - * @inheritDoc - */ - push_back(val: T): void; + /** + * @inheritDoc + */ + push_back(val: T): void; - /** - * Erase the last element. - */ - pop_back(): void; + /** + * Erase the last element. + */ + pop_back(): void; - /** - * Insert a single element. - * - * @param pos Position to insert. - * @param val Value to insert. - * @return An iterator to the newly inserted element. - */ - insert(pos: IteratorT, val: T): IteratorT; + /** + * Insert a single element. + * + * @param pos Position to insert. + * @param val Value to insert. + * @return An iterator to the newly inserted element. + */ + insert(pos: IteratorT, val: T): IteratorT; - /** - * Insert repeated elements. - * - * @param pos Position to insert. - * @param n Number of elements to insert. - * @param val Value to insert repeatedly. - * @return An iterator to the first of the newly inserted elements. - */ - insert(pos: IteratorT, n: number, val: T): IteratorT; + /** + * Insert repeated elements. + * + * @param pos Position to insert. + * @param n Number of elements to insert. + * @param val Value to insert repeatedly. + * @return An iterator to the first of the newly inserted elements. + */ + insert(pos: IteratorT, n: number, val: T): IteratorT; - /** - * Insert range elements. - * - * @param pos Position to insert. - * @param first Input iterator of the first position. - * @param last Input iteartor of the last position. - * @return An iterator to the first of the newly inserted elements. - */ - insert>>( - pos: IteratorT, - first: InputIterator, - last: InputIterator, - ): IteratorT; + /** + * Insert range elements. + * + * @param pos Position to insert. + * @param first Input iterator of the first position. + * @param last Input iteartor of the last position. + * @return An iterator to the first of the newly inserted elements. + */ + insert>>( + pos: IteratorT, + first: InputIterator, + last: InputIterator, + ): IteratorT; } diff --git a/src/internal/container/linear/IListAlgorithm.ts b/src/internal/container/linear/IListAlgorithm.ts index 8534dead..c5e2a1a8 100644 --- a/src/internal/container/linear/IListAlgorithm.ts +++ b/src/internal/container/linear/IListAlgorithm.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -9,57 +10,57 @@ import { Comparator } from "../../functional/Comparator"; import { UnaryPredicator } from "../../functional/UnaryPredicator"; export interface IListAlgorithm { - /* --------------------------------------------------------- + /* --------------------------------------------------------- UNIQUE & REMOVE --------------------------------------------------------- */ - /** - * Remove duplicated elements. - * - * @param binary_pred A binary function predicates two arguments are equal. Default is {@link equal_to}. - */ - unique(binary_pred?: BinaryPredicator): void; + /** + * Remove duplicated elements. + * + * @param binary_pred A binary function predicates two arguments are equal. Default is {@link equal_to}. + */ + unique(binary_pred?: BinaryPredicator): void; - /** - * Remove elements with specific value. - * - * @param val The value to remove. - */ - remove(val: T): void; + /** + * Remove elements with specific value. + * + * @param val The value to remove. + */ + remove(val: T): void; - /** - * Remove elements with specific function. - * - * @param pred A unary function determines whether remove or not. - */ - remove_if(pred: UnaryPredicator): void; + /** + * Remove elements with specific function. + * + * @param pred A unary function determines whether remove or not. + */ + remove_if(pred: UnaryPredicator): void; - /* --------------------------------------------------------- + /* --------------------------------------------------------- SEQUENCE --------------------------------------------------------- */ - /** - * Merge two *sorted* containers. - * - * @param source Source container to transfer. - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. - */ - merge(from: Source, comp?: Comparator): void; + /** + * Merge two *sorted* containers. + * + * @param source Source container to transfer. + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. + */ + merge(from: Source, comp?: Comparator): void; - /** - * Sort elements. - * - * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. - */ - sort(comp?: Comparator): void; + /** + * Sort elements. + * + * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. + */ + sort(comp?: Comparator): void; - /** - * Reverse elements. - */ - reverse(): void; + /** + * Reverse elements. + */ + reverse(): void; - /** - * Swap elements. - * - * @param obj Target container to swap. - */ - swap(obj: Source): void; + /** + * Swap elements. + * + * @param obj Target container to swap. + */ + swap(obj: Source): void; } diff --git a/src/internal/container/linear/ListContainer.ts b/src/internal/container/linear/ListContainer.ts index 76f9dfde..31a1a93f 100644 --- a/src/internal/container/linear/ListContainer.ts +++ b/src/internal/container/linear/ListContainer.ts @@ -1,23 +1,21 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { IContainer } from "../../../base/container/IContainer"; -import { ILinearContainerBase } from "./ILinearContainerBase"; import { Container } from "../../../base/container/Container"; - +import { IContainer } from "../../../base/container/IContainer"; import { IForwardIterator } from "../../../iterator/IForwardIterator"; -import { ReverseIterator } from "../../iterator/ReverseIterator"; -import { ListIterator } from "../../iterator/ListIterator"; - -import { Repeater } from "../../iterator/disposable/Repeater"; -import { NativeArrayIterator } from "../../iterator/disposable/NativeArrayIterator"; import { advance } from "../../../iterator/global"; - import { ErrorGenerator } from "../../exception/ErrorGenerator"; import { Temporary } from "../../functional/Temporary"; +import { ListIterator } from "../../iterator/ListIterator"; +import { ReverseIterator } from "../../iterator/ReverseIterator"; +import { NativeArrayIterator } from "../../iterator/disposable/NativeArrayIterator"; +import { Repeater } from "../../iterator/disposable/Repeater"; +import { ILinearContainerBase } from "./ILinearContainerBase"; /** * Basic List Container. @@ -25,116 +23,110 @@ import { Temporary } from "../../functional/Temporary"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class ListContainer< - T, - SourceT extends IContainer, - IteratorT extends ListIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - T - >, - ReverseIteratorT extends ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - T - >, - > - extends Container - implements ILinearContainerBase + T, + SourceT extends IContainer, + IteratorT extends ListIterator, + ReverseIteratorT extends ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + T + >, + > + extends Container + implements ILinearContainerBase { - private size_!: number; + private size_!: number; - protected begin_!: IteratorT; - protected end_: IteratorT; + protected begin_!: IteratorT; + protected end_: IteratorT; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - protected constructor() { - super(); - - // INIT MEMBERS - this.end_ = this._Create_iterator(null!, null!); - this.clear(); - } - - protected abstract _Create_iterator( - prev: IteratorT, - next: IteratorT, - val?: T, - ): IteratorT; - - /** - * @inheritDoc - */ - public assign(n: number, val: T): void; - - /** - * @inheritDoc - */ - public assign< - InputIterator extends Readonly>, - >(first: InputIterator, last: InputIterator): void; - - public assign(par1: any, par2: any): void { - this.clear(); - this.insert(this.end(), par1, par2); - } - - /** - * @inheritDoc - */ - public clear(): void { - // DISCONNECT NODES - ListIterator._Set_prev(this.end_, this.end_); - ListIterator._Set_next(this.end_, this.end_); - - // RE-SIZE -> 0 - this.begin_ = this.end_; - this.size_ = 0; - } - - /** - * @inheritDoc - */ - public resize(n: number): void { - const expansion: number = n - this.size(); - if (expansion > 0) this.insert(this.end(), expansion, undefined!); - else if (expansion < 0) - this.erase(advance(this.end(), -expansion), this.end()); - } - - /* --------------------------------------------------------- + /** + * Default Constructor. + */ + protected constructor() { + super(); + + // INIT MEMBERS + this.end_ = this._Create_iterator(null!, null!); + this.clear(); + } + + protected abstract _Create_iterator( + prev: IteratorT, + next: IteratorT, + val?: T, + ): IteratorT; + + /** + * @inheritDoc + */ + public assign(n: number, val: T): void; + + /** + * @inheritDoc + */ + public assign< + InputIterator extends Readonly>, + >(first: InputIterator, last: InputIterator): void; + + public assign(par1: any, par2: any): void { + this.clear(); + this.insert(this.end(), par1, par2); + } + + /** + * @inheritDoc + */ + public clear(): void { + // DISCONNECT NODES + ListIterator._Set_prev(this.end_, this.end_); + ListIterator._Set_next(this.end_, this.end_); + + // RE-SIZE -> 0 + this.begin_ = this.end_; + this.size_ = 0; + } + + /** + * @inheritDoc + */ + public resize(n: number): void { + const expansion: number = n - this.size(); + if (expansion > 0) this.insert(this.end(), expansion, undefined!); + else if (expansion < 0) + this.erase(advance(this.end(), -expansion), this.end()); + } + + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public begin(): IteratorT { - return this.begin_; - } - - /** - * @inheritDoc - */ - public end(): IteratorT { - return this.end_; - } - - /** - * @inheritDoc - */ - public size(): number { - return this.size_; - } - - /* ========================================================= + /** + * @inheritDoc + */ + public begin(): IteratorT { + return this.begin_; + } + + /** + * @inheritDoc + */ + public end(): IteratorT { + return this.end_; + } + + /** + * @inheritDoc + */ + public size(): number { + return this.size_; + } + + /* ========================================================= ELEMENTS I/O - PUSH & POP - INSERT @@ -143,197 +135,189 @@ export abstract class ListContainer< ============================================================ PUSH & POP --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public push_front(val: T): void { - this.insert(this.begin_, val); - } - - /** - * @inheritDoc - */ - public push_back(val: T): void { - this.insert(this.end_, val); - } - - /** - * @inheritDoc - */ - public pop_front(): void { - if (this.empty() === true) - throw ErrorGenerator.empty( - this.end_.source().constructor.name, - "pop_front", - ); - - this.erase(this.begin_); - } - - /** - * @inheritDoc - */ - public pop_back(): void { - if (this.empty() === true) - throw ErrorGenerator.empty( - this.end_.source().constructor.name, - "pop_back", - ); - - this.erase(this.end_.prev()); - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public push_front(val: T): void { + this.insert(this.begin_, val); + } + + /** + * @inheritDoc + */ + public push_back(val: T): void { + this.insert(this.end_, val); + } + + /** + * @inheritDoc + */ + public pop_front(): void { + if (this.empty() === true) + throw ErrorGenerator.empty( + this.end_.source().constructor.name, + "pop_front", + ); + + this.erase(this.begin_); + } + + /** + * @inheritDoc + */ + public pop_back(): void { + if (this.empty() === true) + throw ErrorGenerator.empty( + this.end_.source().constructor.name, + "pop_back", + ); + + this.erase(this.end_.prev()); + } + + /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public push(...items: T[]): number { - if (items.length === 0) return this.size(); - - // INSERT BY RANGE - const first: NativeArrayIterator = new NativeArrayIterator(items, 0); - const last: NativeArrayIterator = new NativeArrayIterator( - items, - items.length, - ); - - this._Insert_by_range(this.end(), first, last); - - // RETURN SIZE - return this.size(); - } - - /** - * @inheritDoc - */ - public insert(position: IteratorT, val: T): IteratorT; - /** - * @inheritDoc - */ - public insert(position: IteratorT, size: number, val: T): IteratorT; - /** - * @inheritDoc - */ - public insert< - InputIterator extends Readonly>, - >(position: IteratorT, begin: InputIterator, end: InputIterator): IteratorT; - - public insert(pos: IteratorT, ...args: any[]): IteratorT { - // VALIDATION - if (pos.source() !== this.end_.source()) - throw ErrorGenerator.not_my_iterator(this.end_.source(), "insert"); - else if (pos.erased_ === true) - throw ErrorGenerator.erased_iterator(this.end_.source(), "insert"); - - // BRANCHES - if (args.length === 1) - return this._Insert_by_repeating_val(pos, 1, args[0]); - else if (args.length === 2 && typeof args[0] === "number") - return this._Insert_by_repeating_val(pos, args[0], args[1]); - else return this._Insert_by_range(pos, args[0], args[1]); + /** + * @inheritDoc + */ + public push(...items: T[]): number { + if (items.length === 0) return this.size(); + + // INSERT BY RANGE + const first: NativeArrayIterator = new NativeArrayIterator(items, 0); + const last: NativeArrayIterator = new NativeArrayIterator( + items, + items.length, + ); + + this._Insert_by_range(this.end(), first, last); + + // RETURN SIZE + return this.size(); + } + + /** + * @inheritDoc + */ + public insert(position: IteratorT, val: T): IteratorT; + /** + * @inheritDoc + */ + public insert(position: IteratorT, size: number, val: T): IteratorT; + /** + * @inheritDoc + */ + public insert< + InputIterator extends Readonly>, + >(position: IteratorT, begin: InputIterator, end: InputIterator): IteratorT; + + public insert(pos: IteratorT, ...args: any[]): IteratorT { + // VALIDATION + if (pos.source() !== this.end_.source()) + throw ErrorGenerator.not_my_iterator(this.end_.source(), "insert"); + else if (pos.erased_ === true) + throw ErrorGenerator.erased_iterator(this.end_.source(), "insert"); + + // BRANCHES + if (args.length === 1) + return this._Insert_by_repeating_val(pos, 1, args[0]); + else if (args.length === 2 && typeof args[0] === "number") + return this._Insert_by_repeating_val(pos, args[0], args[1]); + else return this._Insert_by_range(pos, args[0], args[1]); + } + + private _Insert_by_repeating_val( + position: IteratorT, + n: number, + val: T, + ): IteratorT { + const first: Repeater = new Repeater(0, val); + const last: Repeater = new Repeater(n); + + return this._Insert_by_range(position, first, last); + } + + protected _Insert_by_range< + InputIterator extends Readonly>, + >(position: IteratorT, begin: InputIterator, end: InputIterator): IteratorT { + let prev: IteratorT = position.prev(); + let first: IteratorT = null!; + + let size: number = 0; + + for (let it = begin; it.equals(end) === false; it = it.next()) { + // CONSTRUCT ITEM, THE NEW ELEMENT + const item: IteratorT = this._Create_iterator(prev, null!, it.value); + if (size === 0) first = item; + + // PLACE ITEM ON THE NEXT OF "PREV" + ListIterator._Set_next(prev, item); + + // SHIFT CURRENT ITEM TO PREVIOUS + prev = item; + ++size; } - private _Insert_by_repeating_val( - position: IteratorT, - n: number, - val: T, - ): IteratorT { - const first: Repeater = new Repeater(0, val); - const last: Repeater = new Repeater(n); + // WILL FIRST BE THE BEGIN? + if (position.equals(this.begin()) === true) this.begin_ = first; - return this._Insert_by_range(position, first, last); - } + // CONNECT BETWEEN LAST AND POSITION + ListIterator._Set_next(prev, position); + ListIterator._Set_prev(position, prev); - protected _Insert_by_range< - InputIterator extends Readonly>, - >( - position: IteratorT, - begin: InputIterator, - end: InputIterator, - ): IteratorT { - let prev: IteratorT = position.prev(); - let first: IteratorT = null!; - - let size: number = 0; - - for (let it = begin; it.equals(end) === false; it = it.next()) { - // CONSTRUCT ITEM, THE NEW ELEMENT - const item: IteratorT = this._Create_iterator( - prev, - null!, - it.value, - ); - if (size === 0) first = item; - - // PLACE ITEM ON THE NEXT OF "PREV" - ListIterator._Set_next(prev, item); - - // SHIFT CURRENT ITEM TO PREVIOUS - prev = item; - ++size; - } - - // WILL FIRST BE THE BEGIN? - if (position.equals(this.begin()) === true) this.begin_ = first; - - // CONNECT BETWEEN LAST AND POSITION - ListIterator._Set_next(prev, position); - ListIterator._Set_prev(position, prev); - - this.size_ += size; - return first; - } + this.size_ += size; + return first; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public erase(position: IteratorT): IteratorT; - /** - * @inheritDoc - */ - public erase(first: IteratorT, last: IteratorT): IteratorT; - public erase(first: IteratorT, last: IteratorT = first.next()): IteratorT { - return this._Erase_by_range(first, last); + /** + * @inheritDoc + */ + public erase(position: IteratorT): IteratorT; + /** + * @inheritDoc + */ + public erase(first: IteratorT, last: IteratorT): IteratorT; + public erase(first: IteratorT, last: IteratorT = first.next()): IteratorT { + return this._Erase_by_range(first, last); + } + + protected _Erase_by_range(first: IteratorT, last: IteratorT): IteratorT { + // VALIDATION + if (first.source() !== this.end_.source()) + throw ErrorGenerator.not_my_iterator(this.end_.source(), "insert"); + else if (first.erased_ === true) + throw ErrorGenerator.erased_iterator(this.end_.source(), "insert"); + else if (first.equals(this.end_)) return this.end_; + + // FIND PREV AND NEXT + const prev: IteratorT = first.prev(); + + // SHRINK + ListIterator._Set_next(prev, last); + ListIterator._Set_prev(last, prev); + + for (let it = first; !it.equals(last); it = it.next()) { + it.erased_ = true; + --this.size_; } + if (first.equals(this.begin_)) this.begin_ = last; - protected _Erase_by_range(first: IteratorT, last: IteratorT): IteratorT { - // VALIDATION - if (first.source() !== this.end_.source()) - throw ErrorGenerator.not_my_iterator(this.end_.source(), "insert"); - else if (first.erased_ === true) - throw ErrorGenerator.erased_iterator(this.end_.source(), "insert"); - else if (first.equals(this.end_)) return this.end_; + return last; + } - // FIND PREV AND NEXT - const prev: IteratorT = first.prev(); - - // SHRINK - ListIterator._Set_next(prev, last); - ListIterator._Set_prev(last, prev); - - for (let it = first; !it.equals(last); it = it.next()) { - it.erased_ = true; - --this.size_; - } - if (first.equals(this.begin_)) this.begin_ = last; - - return last; - } - - /* --------------------------------------------------------- + /* --------------------------------------------------------- SWAP --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public swap(obj: SourceT): void { - [this.begin_, (obj as any).begin_] = [(obj as any).begin_, this.begin_]; - [this.end_, (obj as any).end_] = [(obj as any).end_, this.end_]; - [this.size_, (obj as any).size_] = [(obj as any).size_, this.size_]; - } + /** + * @inheritDoc + */ + public swap(obj: SourceT): void { + [this.begin_, (obj as any).begin_] = [(obj as any).begin_, this.begin_]; + [this.end_, (obj as any).end_] = [(obj as any).end_, this.end_]; + [this.size_, (obj as any).size_] = [(obj as any).size_, this.size_]; + } } diff --git a/src/internal/container/linear/VectorContainer.ts b/src/internal/container/linear/VectorContainer.ts index 5655069d..c4f4e544 100644 --- a/src/internal/container/linear/VectorContainer.ts +++ b/src/internal/container/linear/VectorContainer.ts @@ -1,209 +1,205 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { ArrayContainer } from "./ArrayContainer"; - import { IContainer } from "../../../base/container/IContainer"; import { IForwardIterator } from "../../../iterator/IForwardIterator"; import { ArrayIteratorBase } from "../../iterator/ArrayIteratorBase"; import { ArrayReverseIteratorBase } from "../../iterator/ArrayReverseIteratorBase"; +import { ArrayContainer } from "./ArrayContainer"; export abstract class VectorContainer< + T, + SourceT extends IContainer, + ArrayT extends VectorContainer, + IteratorT extends ArrayIteratorBase< + T, + SourceT, + ArrayT, + IteratorT, + ReverseT, + T + >, + ReverseT extends ArrayReverseIteratorBase< T, - SourceT extends IContainer, - ArrayT extends VectorContainer, - IteratorT extends ArrayIteratorBase< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - T - >, - ReverseT extends ArrayReverseIteratorBase< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - T - >, + SourceT, + ArrayT, + IteratorT, + ReverseT, + T + >, > extends ArrayContainer { - protected data_!: T[]; + protected data_!: T[]; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - protected constructor() { - super(); - } - - /** - * @inheritDoc - */ - public assign(n: number, val: T): void; - /** - * @inheritDoc - */ - public assign< - InputIterator extends Readonly>, - >(begin: InputIterator, end: InputIterator): void; - - public assign(first: any, second: any): void { - this.clear(); - this.insert(this.end(), first, second); - } - - /** - * @inheritDoc - */ - public clear(): void { - this.data_.splice(0, this.data_.length); - } - - /** - * @inheritDoc - */ - public resize(n: number) { - this.data_.length = n; - } - - /* ========================================================= + /** + * Default Constructor. + */ + protected constructor() { + super(); + } + + /** + * @inheritDoc + */ + public assign(n: number, val: T): void; + /** + * @inheritDoc + */ + public assign< + InputIterator extends Readonly>, + >(begin: InputIterator, end: InputIterator): void; + + public assign(first: any, second: any): void { + this.clear(); + this.insert(this.end(), first, second); + } + + /** + * @inheritDoc + */ + public clear(): void { + this.data_.splice(0, this.data_.length); + } + + /** + * @inheritDoc + */ + public resize(n: number) { + this.data_.length = n; + } + + /* ========================================================= ACCESSORS ========================================================= */ - /** - * @inheritDoc - */ - public size(): number { - return this.data_.length; - } - - protected _At(index: number): T { - return this.data_[index]; - } - - protected _Set(index: number, val: T): void { - this.data_[index] = val; - } - - /** - * Access data. - * - * @return An array capsuled by this {@link Vector}. - */ - public data(): Array { - return this.data_; - } - - /** - * @inheritDoc - */ - public [Symbol.iterator](): IterableIterator { - return this.data_[Symbol.iterator](); - } - - /* ========================================================= + /** + * @inheritDoc + */ + public size(): number { + return this.data_.length; + } + + protected _At(index: number): T { + return this.data_[index]; + } + + protected _Set(index: number, val: T): void { + this.data_[index] = val; + } + + /** + * Access data. + * + * @return An array capsuled by this {@link Vector}. + */ + public data(): Array { + return this.data_; + } + + /** + * @inheritDoc + */ + public [Symbol.iterator](): IterableIterator { + return this.data_[Symbol.iterator](); + } + + /* ========================================================= ELEMENTS I/O - INSERT - ERASE ============================================================ INSERT --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public push(...items: T[]): number { - return this.data_.push(...items); - } - - /** - * @inheritDoc - */ - public push_back(val: T): void { - this.data_.push(val); - } - - protected _Insert_by_range< - InputIterator extends Readonly>, - >( - position: IteratorT, - first: InputIterator, - last: InputIterator, - ): IteratorT { - if (position.index() >= this.size()) { - // WHEN INSERT TO THE LAST - const prev_size: number = this.size(); - - for (; !first.equals(last); first = first.next()) - this.data_.push(first.value); - - return this.nth(prev_size); - } else { - //---- - // INSERT TO THE MIDDLE POSITION - //---- - // CUT RIGHT SIDE - const spliced_array: T[] = this.data_.splice(position.index()); - - // INSERT ELEMENTS - for (; !first.equals(last); first = first.next()) - this.data_.push(first.value); - - this.data_.push(...spliced_array); // CONCAT THE SPLICEDS - - return position; - } - } - - /* --------------------------------------------------------- + /** + * @inheritDoc + */ + public push(...items: T[]): number { + return this.data_.push(...items); + } + + /** + * @inheritDoc + */ + public push_back(val: T): void { + this.data_.push(val); + } + + protected _Insert_by_range< + InputIterator extends Readonly>, + >(position: IteratorT, first: InputIterator, last: InputIterator): IteratorT { + if (position.index() >= this.size()) { + // WHEN INSERT TO THE LAST + const prev_size: number = this.size(); + + for (; !first.equals(last); first = first.next()) + this.data_.push(first.value); + + return this.nth(prev_size); + } else { + //---- + // INSERT TO THE MIDDLE POSITION + //---- + // CUT RIGHT SIDE + const spliced_array: T[] = this.data_.splice(position.index()); + + // INSERT ELEMENTS + for (; !first.equals(last); first = first.next()) + this.data_.push(first.value); + + this.data_.push(...spliced_array); // CONCAT THE SPLICEDS + + return position; + } + } + + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - protected _Pop_back(): void { - this.data_.pop(); - } + protected _Pop_back(): void { + this.data_.pop(); + } - protected _Erase_by_range(first: IteratorT, last: IteratorT): IteratorT { - if (first.index() >= this.size()) return first; + protected _Erase_by_range(first: IteratorT, last: IteratorT): IteratorT { + if (first.index() >= this.size()) return first; - // ERASE ELEMENTS - if (last.index() >= this.size()) { - this.data_.splice(first.index()); - return this.end(); - } else this.data_.splice(first.index(), last.index() - first.index()); + // ERASE ELEMENTS + if (last.index() >= this.size()) { + this.data_.splice(first.index()); + return this.end(); + } else this.data_.splice(first.index(), last.index() - first.index()); - return first; - } + return first; + } - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- UTILITIES --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public equals(obj: SourceT): boolean { - return this.data_ === ((obj) as this).data_; - } - - /** - * @inheritDoc - */ - public swap(obj: SourceT): void { - [this.data_, ((obj) as this).data_] = [ - ((obj) as this).data_, - this.data_, - ]; - } - - /** - * @inheritDoc - */ - public toJSON(): Array { - return this.data_; - } + /** + * @inheritDoc + */ + public equals(obj: SourceT): boolean { + return this.data_ === ((obj) as this).data_; + } + + /** + * @inheritDoc + */ + public swap(obj: SourceT): void { + [this.data_, ((obj) as this).data_] = [ + ((obj) as this).data_, + this.data_, + ]; + } + + /** + * @inheritDoc + */ + public toJSON(): Array { + return this.data_; + } } diff --git a/src/internal/container/partial/IClear.ts b/src/internal/container/partial/IClear.ts index 8efcaef2..871c7f7f 100644 --- a/src/internal/container/partial/IClear.ts +++ b/src/internal/container/partial/IClear.ts @@ -5,8 +5,8 @@ */ //================================================================ export interface IClear { - /** - * Clear elements. - */ - clear(): void; + /** + * Clear elements. + */ + clear(): void; } diff --git a/src/internal/container/partial/IDeque.ts b/src/internal/container/partial/IDeque.ts index 8543617e..785a447e 100644 --- a/src/internal/container/partial/IDeque.ts +++ b/src/internal/container/partial/IDeque.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -7,8 +8,8 @@ import { IPushFront } from "./IPushFront"; export interface IDeque extends IPushFront { - /** - * Erase the first element. - */ - pop_front(): void; + /** + * Erase the first element. + */ + pop_front(): void; } diff --git a/src/internal/container/partial/IEmpty.ts b/src/internal/container/partial/IEmpty.ts index 326a797c..699ed9b5 100644 --- a/src/internal/container/partial/IEmpty.ts +++ b/src/internal/container/partial/IEmpty.ts @@ -5,8 +5,8 @@ */ //================================================================ export interface IEmpty { - /** - * Test whether container is empty. - */ - empty(): boolean; + /** + * Test whether container is empty. + */ + empty(): boolean; } diff --git a/src/internal/container/partial/IFront.ts b/src/internal/container/partial/IFront.ts index b7973c7b..7017c09d 100644 --- a/src/internal/container/partial/IFront.ts +++ b/src/internal/container/partial/IFront.ts @@ -5,17 +5,17 @@ */ //================================================================ export interface IFront { - /** - * Get the first element. - * - * @return The first element. - */ - front(): T; + /** + * Get the first element. + * + * @return The first element. + */ + front(): T; - /** - * Change the first element. - * - * @param val The value to change. - */ - front(val: T): void; + /** + * Change the first element. + * + * @param val The value to change. + */ + front(val: T): void; } diff --git a/src/internal/container/partial/IInsert.ts b/src/internal/container/partial/IInsert.ts index 5a4864cd..0e3b3e95 100644 --- a/src/internal/container/partial/IInsert.ts +++ b/src/internal/container/partial/IInsert.ts @@ -1,14 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { IForwardIterator } from "../../../iterator/IForwardIterator"; import { IPointer } from "../../../functional/IPointer"; +import { IForwardIterator } from "../../../iterator/IForwardIterator"; export interface IInsert< - Iterator extends IForwardIterator, Iterator>, + Iterator extends IForwardIterator, Iterator>, > { - insert(it: Iterator, value: IPointer.ValueType): Iterator; + insert(it: Iterator, value: IPointer.ValueType): Iterator; } diff --git a/src/internal/container/partial/IPush.ts b/src/internal/container/partial/IPush.ts index d763ba96..eeba5327 100644 --- a/src/internal/container/partial/IPush.ts +++ b/src/internal/container/partial/IPush.ts @@ -5,11 +5,11 @@ */ //================================================================ export interface IPush { - /** - * Insert items at the end. - * - * @param items Items to insert. - * @return Number of elements in the container after insertion. - */ - push(...items: T[]): number; + /** + * Insert items at the end. + * + * @param items Items to insert. + * @return Number of elements in the container after insertion. + */ + push(...items: T[]): number; } diff --git a/src/internal/container/partial/IPushBack.ts b/src/internal/container/partial/IPushBack.ts index 65f96ee1..77762ad7 100644 --- a/src/internal/container/partial/IPushBack.ts +++ b/src/internal/container/partial/IPushBack.ts @@ -5,17 +5,17 @@ */ //================================================================ export interface IPushBack { - /** - * Insert an element at the end. - * - * @param val Value to insert. - */ - push_back(val: T): void; + /** + * Insert an element at the end. + * + * @param val Value to insert. + */ + push_back(val: T): void; } export namespace IPushBack { - export type ContainerType> = - Range extends IPushBack ? Range : unknown; + export type ContainerType> = + Range extends IPushBack ? Range : unknown; - export type IteratorType> = - Range extends IPushBack ? Iterator : unknown; + export type IteratorType> = + Range extends IPushBack ? Iterator : unknown; } diff --git a/src/internal/container/partial/IPushFront.ts b/src/internal/container/partial/IPushFront.ts index dafeb6e8..f8dc921e 100644 --- a/src/internal/container/partial/IPushFront.ts +++ b/src/internal/container/partial/IPushFront.ts @@ -5,10 +5,10 @@ */ //================================================================ export interface IPushFront { - /** - * Insert an element at the first. - * - * @param val Value to insert. - */ - push_front(val: T): void; + /** + * Insert an element at the first. + * + * @param val Value to insert. + */ + push_front(val: T): void; } diff --git a/src/internal/container/partial/ISize.ts b/src/internal/container/partial/ISize.ts index 8d6f22fa..b898e543 100644 --- a/src/internal/container/partial/ISize.ts +++ b/src/internal/container/partial/ISize.ts @@ -5,8 +5,8 @@ */ //================================================================ export interface ISize { - /** - * Number of elements in the container. - */ - size(): number; + /** + * Number of elements in the container. + */ + size(): number; } diff --git a/src/internal/exception/ErrorGenerator.ts b/src/internal/exception/ErrorGenerator.ts index 62404b38..d53a7f48 100644 --- a/src/internal/exception/ErrorGenerator.ts +++ b/src/internal/exception/ErrorGenerator.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -8,115 +9,113 @@ import { InvalidArgument } from "../../exception/InvalidArgument"; import { OutOfRange } from "../../exception/OutOfRange"; export namespace ErrorGenerator { - /* --------------------------------------------------------- + /* --------------------------------------------------------- COMMON --------------------------------------------------------- */ - export function get_class_name(instance: string | Instance): string { - if (typeof instance === "string") return instance; + export function get_class_name(instance: string | Instance): string { + if (typeof instance === "string") return instance; - let ret: string = instance.constructor.name; - if (instance.constructor.__MODULE) - ret = `${instance.constructor.__MODULE}.${ret}`; + let ret: string = instance.constructor.name; + if (instance.constructor.__MODULE) + ret = `${instance.constructor.__MODULE}.${ret}`; - return `std.${ret}`; - } + return `std.${ret}`; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONTAINERS --------------------------------------------------------- */ - export function empty(instance: Instance, method: string): OutOfRange { - return new OutOfRange( - `Error on ${get_class_name( - instance, - )}.${method}(): it's empty container.`, - ); - } + export function empty(instance: Instance, method: string): OutOfRange { + return new OutOfRange( + `Error on ${get_class_name(instance)}.${method}(): it's empty container.`, + ); + } - export function negative_index( - instance: Instance, - method: string, - index: number, - ): OutOfRange { - return new OutOfRange( - `Error on ${get_class_name( - instance, - )}.${method}(): parametric index is negative -> (index = ${index}).`, - ); - } + export function negative_index( + instance: Instance, + method: string, + index: number, + ): OutOfRange { + return new OutOfRange( + `Error on ${get_class_name( + instance, + )}.${method}(): parametric index is negative -> (index = ${index}).`, + ); + } - export function excessive_index( - instance: Instance, - method: string, - index: number, - size: number, - ): OutOfRange { - return new OutOfRange( - `Error on ${get_class_name( - instance, - )}.${method}(): parametric index is equal or greater than size -> (index = ${index}, size: ${size}).`, - ); - } + export function excessive_index( + instance: Instance, + method: string, + index: number, + size: number, + ): OutOfRange { + return new OutOfRange( + `Error on ${get_class_name( + instance, + )}.${method}(): parametric index is equal or greater than size -> (index = ${index}, size: ${size}).`, + ); + } - export function not_my_iterator( - instance: Instance, - method: string, - ): InvalidArgument { - return new InvalidArgument( - `Error on ${get_class_name( - instance, - )}.${method}(): parametric iterator is not this container's own.`, - ); - } + export function not_my_iterator( + instance: Instance, + method: string, + ): InvalidArgument { + return new InvalidArgument( + `Error on ${get_class_name( + instance, + )}.${method}(): parametric iterator is not this container's own.`, + ); + } - export function erased_iterator( - instance: Instance, - method: string, - ): InvalidArgument { - return new InvalidArgument( - `Error on ${get_class_name( - instance, - )}.${method}(): parametric iterator, it already has been erased.`, - ); - } + export function erased_iterator( + instance: Instance, + method: string, + ): InvalidArgument { + return new InvalidArgument( + `Error on ${get_class_name( + instance, + )}.${method}(): parametric iterator, it already has been erased.`, + ); + } - export function negative_iterator( - instance: Instance, - method: string, - index: number, - ): OutOfRange { - return new OutOfRange( - `Error on ${get_class_name( - instance, - )}.${method}(): parametric iterator is directing negative position -> (index = ${index}).`, - ); - } + export function negative_iterator( + instance: Instance, + method: string, + index: number, + ): OutOfRange { + return new OutOfRange( + `Error on ${get_class_name( + instance, + )}.${method}(): parametric iterator is directing negative position -> (index = ${index}).`, + ); + } - export function iterator_end_value( - instance: Instance, - method: string = "end", - ): OutOfRange { - const className: string = get_class_name(instance); - return new OutOfRange( - `Error on ${className}.Iterator.value: cannot access to the ${className}.${method}().value.`, - ); - } + export function iterator_end_value( + instance: Instance, + method: string = "end", + ): OutOfRange { + const className: string = get_class_name(instance); + return new OutOfRange( + `Error on ${className}.Iterator.value: cannot access to the ${className}.${method}().value.`, + ); + } - export function key_nout_found( - instance: Instance, - method: string, - key: Key, - ): OutOfRange { - throw new OutOfRange( - `Error on ${get_class_name( - instance, - )}.${method}(): unable to find the matched key -> ${key}`, - ); - } + export function key_nout_found( + instance: Instance, + method: string, + key: Key, + ): OutOfRange { + throw new OutOfRange( + `Error on ${get_class_name( + instance, + )}.${method}(): unable to find the matched key -> ${key}`, + ); + } } interface Instance { - constructor: { - name: string; - __MODULE?: string; - }; + constructor: { + name: string; + __MODULE?: string; + }; } diff --git a/src/internal/exception/ErrorInstance.ts b/src/internal/exception/ErrorInstance.ts index 21322bcb..84a26550 100644 --- a/src/internal/exception/ErrorInstance.ts +++ b/src/internal/exception/ErrorInstance.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -12,96 +13,96 @@ import { ErrorCategory } from "../../exception/ErrorCategory"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class ErrorInstance { - protected category_!: ErrorCategory; - protected value_!: number; + protected category_!: ErrorCategory; + protected value_!: number; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor(); + /** + * Default Constructor. + */ + public constructor(); - /** - * Initializer Constructor. - * - * @param val Identifier of an error instance. - * @param category An error category instance. - */ - public constructor(val: number, category: ErrorCategory); + /** + * Initializer Constructor. + * + * @param val Identifier of an error instance. + * @param category An error category instance. + */ + public constructor(val: number, category: ErrorCategory); - public constructor(val: number = 0, category: ErrorCategory | null = null) { - this.assign(val, category!); - } + public constructor(val: number = 0, category: ErrorCategory | null = null) { + this.assign(val, category!); + } - /** - * Assign content. - * - * @param val Identifier of an error condition. - * @param category An error category instance. - */ - public assign(val: number, category: ErrorCategory): void { - this.category_ = category; - this.value_ = val; - } + /** + * Assign content. + * + * @param val Identifier of an error condition. + * @param category An error category instance. + */ + public assign(val: number, category: ErrorCategory): void { + this.category_ = category; + this.value_ = val; + } - /** - * Clear content. - */ - public clear(): void { - this.value_ = 0; - } + /** + * Clear content. + */ + public clear(): void { + this.value_ = 0; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * Get category. - * - * @return The category object. - */ - public category(): ErrorCategory { - return this.category_!; - } + /** + * Get category. + * + * @return The category object. + */ + public category(): ErrorCategory { + return this.category_!; + } - /** - * Get value, the identifier. - * - * @return The value, identifier of this object. - */ - public value(): number { - return this.value_; - } + /** + * Get value, the identifier. + * + * @return The value, identifier of this object. + */ + public value(): number { + return this.value_; + } - /** - * Get message. - * - * @return The message. - */ - public message(): string { - return this.category_!.message(this.value_); - } + /** + * Get message. + * + * @return The message. + */ + public message(): string { + return this.category_!.message(this.value_); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- OPERATORS --------------------------------------------------------- */ - /** - * Covert bo bool. - * - * @return Whether the {@link value} is not zero. - */ - public to_bool(): boolean { - return this.value_ !== 0; - } + /** + * Covert bo bool. + * + * @return Whether the {@link value} is not zero. + */ + public to_bool(): boolean { + return this.value_ !== 0; + } - public toJSON(): object { - if (this.category_ === null) return {}; - else - return { - cateogory: this.category_.name(), - value: this.value(), - message: this.message(), - }; - } + public toJSON(): object { + if (this.category_ === null) return {}; + else + return { + cateogory: this.category_.name(), + value: this.value(), + message: this.message(), + }; + } } diff --git a/src/internal/hash/HashBuckets.ts b/src/internal/hash/HashBuckets.ts index 18dad800..375e19ce 100644 --- a/src/internal/hash/HashBuckets.ts +++ b/src/internal/hash/HashBuckets.ts @@ -1,10 +1,10 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ - import { Hasher } from "../functional/Hasher"; /** @@ -13,116 +13,115 @@ import { Hasher } from "../functional/Hasher"; * @author Jeongho Nam - https://github.com/samchon */ export class HashBuckets { - private readonly fetcher_: Fetcher; - private readonly hasher_: Hasher; + private readonly fetcher_: Fetcher; + private readonly hasher_: Hasher; - private max_load_factor_: number; - private data_: Elem[][]; - private size_: number; + private max_load_factor_: number; + private data_: Elem[][]; + private size_: number; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - public constructor(fetcher: Fetcher, hasher: Hasher) { - this.fetcher_ = fetcher; - this.hasher_ = hasher; - - this.max_load_factor_ = DEFAULT_MAX_FACTOR; - this.data_ = []; - this.size_ = 0; - - this.initialize(); + public constructor(fetcher: Fetcher, hasher: Hasher) { + this.fetcher_ = fetcher; + this.hasher_ = hasher; + + this.max_load_factor_ = DEFAULT_MAX_FACTOR; + this.data_ = []; + this.size_ = 0; + + this.initialize(); + } + + public clear(): void { + this.data_ = []; + this.size_ = 0; + + this.initialize(); + } + + public rehash(length: number): void { + length = Math.max(length, MIN_BUCKET_COUNT); + + const data: Elem[][] = []; + for (let i: number = 0; i < length; ++i) data.push([]); + + for (const row of this.data_) + for (const elem of row) { + const index: number = this.hasher_(this.fetcher_(elem)) % data.length; + data[index].push(elem); + } + this.data_ = data; + } + + public reserve(length: number): void { + if (length > this.capacity()) { + length = Math.floor(length / this.max_load_factor_); + this.rehash(length); } + } - public clear(): void { - this.data_ = []; - this.size_ = 0; + private initialize(): void { + for (let i: number = 0; i < MIN_BUCKET_COUNT; ++i) this.data_.push([]); + } - this.initialize(); - } - - public rehash(length: number): void { - length = Math.max(length, MIN_BUCKET_COUNT); - - const data: Elem[][] = []; - for (let i: number = 0; i < length; ++i) data.push([]); - - for (const row of this.data_) - for (const elem of row) { - const index: number = - this.hasher_(this.fetcher_(elem)) % data.length; - data[index].push(elem); - } - this.data_ = data; - } - - public reserve(length: number): void { - if (length > this.capacity()) { - length = Math.floor(length / this.max_load_factor_); - this.rehash(length); - } - } - - private initialize(): void { - for (let i: number = 0; i < MIN_BUCKET_COUNT; ++i) this.data_.push([]); - } - - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - public length(): number { - return this.data_.length; - } - - public capacity(): number { - return this.data_.length * this.max_load_factor_; - } - - public at(index: number): Elem[] { - return this.data_[index]; - } - - public load_factor(): number { - return this.size_ / this.length(); - } - - public max_load_factor(): number; - public max_load_factor(z: number): void; - public max_load_factor(z: number | null = null): number | void { - if (z === null) return this.max_load_factor_; - else this.max_load_factor_ = z; - } - - public hash_function(): Hasher { - return this.hasher_; - } - - /* --------------------------------------------------------- + public length(): number { + return this.data_.length; + } + + public capacity(): number { + return this.data_.length * this.max_load_factor_; + } + + public at(index: number): Elem[] { + return this.data_[index]; + } + + public load_factor(): number { + return this.size_ / this.length(); + } + + public max_load_factor(): number; + public max_load_factor(z: number): void; + public max_load_factor(z: number | null = null): number | void { + if (z === null) return this.max_load_factor_; + else this.max_load_factor_ = z; + } + + public hash_function(): Hasher { + return this.hasher_; + } + + /* --------------------------------------------------------- ELEMENTS I/O --------------------------------------------------------- */ - private index(elem: Elem): number { - return this.hasher_(this.fetcher_(elem)) % this.length(); - } - - public insert(val: Elem): void { - const capacity: number = this.capacity(); - if (++this.size_ > capacity) this.reserve(capacity * 2); - - const index: number = this.index(val); - this.data_[index].push(val); - } - - public erase(val: Elem): void { - const index: number = this.index(val); - const bucket: Elem[] = this.data_[index]; - - for (let i: number = 0; i < bucket.length; ++i) - if (bucket[i] === val) { - bucket.splice(i, 1); - --this.size_; - break; - } - } + private index(elem: Elem): number { + return this.hasher_(this.fetcher_(elem)) % this.length(); + } + + public insert(val: Elem): void { + const capacity: number = this.capacity(); + if (++this.size_ > capacity) this.reserve(capacity * 2); + + const index: number = this.index(val); + this.data_[index].push(val); + } + + public erase(val: Elem): void { + const index: number = this.index(val); + const bucket: Elem[] = this.data_[index]; + + for (let i: number = 0; i < bucket.length; ++i) + if (bucket[i] === val) { + bucket.splice(i, 1); + --this.size_; + break; + } + } } const MIN_BUCKET_COUNT = 10; diff --git a/src/internal/hash/MapHashBuckets.ts b/src/internal/hash/MapHashBuckets.ts index 84eec82a..1d536c6f 100644 --- a/src/internal/hash/MapHashBuckets.ts +++ b/src/internal/hash/MapHashBuckets.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { HashBuckets } from "./HashBuckets"; - import { IHashMap } from "../../base/container/IHashMap"; import { Comparator } from "../functional/Comparator"; import { Hasher } from "../functional/Hasher"; +import { HashBuckets } from "./HashBuckets"; /** * Hash buckets for map containers. @@ -16,73 +16,72 @@ import { Hasher } from "../functional/Hasher"; * @author Jeongho Nam - https://github.com/samchon */ export class MapHashBuckets< - Key, - T, - Unique extends boolean, - Source extends IHashMap, + Key, + T, + Unique extends boolean, + Source extends IHashMap, > extends HashBuckets> { - private source_: IHashMap; - private readonly key_eq_: Comparator; + private source_: IHashMap; + private readonly key_eq_: Comparator; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Initializer Constructor - * - * @param source Source map container - * @param hasher Hash function - * @param pred Equality function - */ - public constructor( - source: Source, - hasher: Hasher, - pred: Comparator, - ) { - super(fetcher, hasher); + /** + * Initializer Constructor + * + * @param source Source map container + * @param hasher Hash function + * @param pred Equality function + */ + public constructor( + source: Source, + hasher: Hasher, + pred: Comparator, + ) { + super(fetcher, hasher); - this.source_ = source; - this.key_eq_ = pred; - } + this.source_ = source; + this.key_eq_ = pred; + } - /** - * @internal - */ - public static _Swap_source< - Key, - T, - Unique extends boolean, - Source extends IHashMap, - >( - x: MapHashBuckets, - y: MapHashBuckets, - ): void { - [x.source_, y.source_] = [y.source_, x.source_]; - } + /** + * @internal + */ + public static _Swap_source< + Key, + T, + Unique extends boolean, + Source extends IHashMap, + >( + x: MapHashBuckets, + y: MapHashBuckets, + ): void { + [x.source_, y.source_] = [y.source_, x.source_]; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- FINDERS --------------------------------------------------------- */ - public key_eq(): Comparator { - return this.key_eq_; - } + public key_eq(): Comparator { + return this.key_eq_; + } - public find(key: Key): IHashMap.Iterator { - const index: number = this.hash_function()(key) % this.length(); - const bucket: IHashMap.Iterator[] = - this.at(index); + public find(key: Key): IHashMap.Iterator { + const index: number = this.hash_function()(key) % this.length(); + const bucket: IHashMap.Iterator[] = this.at(index); - for (const it of bucket) if (this.key_eq_(it.first, key)) return it; + for (const it of bucket) if (this.key_eq_(it.first, key)) return it; - return this.source_.end(); - } + return this.source_.end(); + } } function fetcher< - Key, - T, - Unique extends boolean, - Source extends IHashMap, + Key, + T, + Unique extends boolean, + Source extends IHashMap, >(elem: IHashMap.Iterator): Key { - return elem.first; + return elem.first; } diff --git a/src/internal/hash/SetHashBuckets.ts b/src/internal/hash/SetHashBuckets.ts index 57138de8..bf0ebd11 100644 --- a/src/internal/hash/SetHashBuckets.ts +++ b/src/internal/hash/SetHashBuckets.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { HashBuckets } from "./HashBuckets"; - import { IHashSet } from "../../base/container/IHashSet"; import { Comparator } from "../functional/Comparator"; import { Hasher } from "../functional/Hasher"; +import { HashBuckets } from "./HashBuckets"; /** * Hash buckets for set containers @@ -16,69 +16,69 @@ import { Hasher } from "../functional/Hasher"; * @author Jeongho Nam - https://github.com/samchon */ export class SetHashBuckets< - Key, - Unique extends boolean, - Source extends IHashSet, + Key, + Unique extends boolean, + Source extends IHashSet, > extends HashBuckets> { - private source_: IHashSet; - private readonly key_eq_: Comparator; + private source_: IHashSet; + private readonly key_eq_: Comparator; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Initializer Constructor - * - * @param source Source set container - * @param hasher Hash function - * @param pred Equality function - */ - public constructor( - source: IHashSet, - hasher: Hasher, - pred: Comparator, - ) { - super(fetcher, hasher); + /** + * Initializer Constructor + * + * @param source Source set container + * @param hasher Hash function + * @param pred Equality function + */ + public constructor( + source: IHashSet, + hasher: Hasher, + pred: Comparator, + ) { + super(fetcher, hasher); - this.source_ = source; - this.key_eq_ = pred; - } + this.source_ = source; + this.key_eq_ = pred; + } - /** - * @internal - */ - public static _Swap_source< - Key, - Unique extends boolean, - Source extends IHashSet, - >( - x: SetHashBuckets, - y: SetHashBuckets, - ): void { - [x.source_, y.source_] = [y.source_, x.source_]; - } + /** + * @internal + */ + public static _Swap_source< + Key, + Unique extends boolean, + Source extends IHashSet, + >( + x: SetHashBuckets, + y: SetHashBuckets, + ): void { + [x.source_, y.source_] = [y.source_, x.source_]; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- FINDERS --------------------------------------------------------- */ - public key_eq(): Comparator { - return this.key_eq_; - } + public key_eq(): Comparator { + return this.key_eq_; + } - public find(val: Key): IHashSet.Iterator { - const index: number = this.hash_function()(val) % this.length(); - const bucket: IHashSet.Iterator[] = this.at(index); + public find(val: Key): IHashSet.Iterator { + const index: number = this.hash_function()(val) % this.length(); + const bucket: IHashSet.Iterator[] = this.at(index); - for (const it of bucket) if (this.key_eq_(it.value, val)) return it; + for (const it of bucket) if (this.key_eq_(it.value, val)) return it; - return this.source_.end(); - } + return this.source_.end(); + } } function fetcher< - Key, - Unique extends boolean, - Source extends IHashSet, + Key, + Unique extends boolean, + Source extends IHashSet, >(elem: IHashSet.Iterator): Key { - return elem.value; + return elem.value; } diff --git a/src/internal/iterator/ArrayIterator.ts b/src/internal/iterator/ArrayIterator.ts index efadaeb3..95a7a1d4 100644 --- a/src/internal/iterator/ArrayIterator.ts +++ b/src/internal/iterator/ArrayIterator.ts @@ -1,53 +1,53 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ import { IArrayContainer } from "../../base/container/IArrayContainer"; -import { ArrayIteratorBase } from "./ArrayIteratorBase"; - import { ArrayContainer } from "../container/linear/ArrayContainer"; +import { ArrayIteratorBase } from "./ArrayIteratorBase"; import { ArrayReverseIterator } from "./ArrayReverseIterator"; export class ArrayIterator< - T, - SourceT extends ArrayContainer< - T, - SourceT, - SourceT, - ArrayIterator, - ArrayReverseIterator, - T - >, - > - extends ArrayIteratorBase< - T, - SourceT, - SourceT, - ArrayIterator, - ArrayReverseIterator, - T + T, + SourceT extends ArrayContainer< + T, + SourceT, + SourceT, + ArrayIterator, + ArrayReverseIterator, + T + >, + > + extends ArrayIteratorBase< + T, + SourceT, + SourceT, + ArrayIterator, + ArrayReverseIterator, + T + > + implements + IArrayContainer.Iterator< + T, + SourceT, + ArrayIterator, + ArrayReverseIterator > - implements - IArrayContainer.Iterator< - T, - SourceT, - ArrayIterator, - ArrayReverseIterator - > { - /** - * @inheritDoc - */ - public reverse(): ArrayReverseIterator { - return new ArrayReverseIterator(this); - } + /** + * @inheritDoc + */ + public reverse(): ArrayReverseIterator { + return new ArrayReverseIterator(this); + } - /** - * @inheritDoc - */ - public source(): SourceT { - return this._Get_array(); - } + /** + * @inheritDoc + */ + public source(): SourceT { + return this._Get_array(); + } } diff --git a/src/internal/iterator/ArrayIteratorBase.ts b/src/internal/iterator/ArrayIteratorBase.ts index 7b9742e9..4addb92b 100644 --- a/src/internal/iterator/ArrayIteratorBase.ts +++ b/src/internal/iterator/ArrayIteratorBase.ts @@ -1,15 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ import { IContainer } from "../../base/container/IContainer"; +import { equal_to } from "../../functional/comparators"; import { IRandomAccessIterator } from "../../iterator/IRandomAccessIterator"; - import { ArrayContainer } from "../container/linear/ArrayContainer"; import { ArrayReverseIteratorBase } from "./ArrayReverseIteratorBase"; -import { equal_to } from "../../functional/comparators"; /** * Iterator of Array Containers. @@ -17,126 +17,119 @@ import { equal_to } from "../../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class ArrayIteratorBase< - T extends ElemT, - SourceT extends IContainer, - ArrayT extends ArrayContainer< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - ElemT - >, - IteratorT extends ArrayIteratorBase< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - ElemT - >, - ReverseT extends ArrayReverseIteratorBase< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - ElemT - >, - ElemT, + T extends ElemT, + SourceT extends IContainer, + ArrayT extends ArrayContainer, + IteratorT extends ArrayIteratorBase< + T, + SourceT, + ArrayT, + IteratorT, + ReverseT, + ElemT + >, + ReverseT extends ArrayReverseIteratorBase< + T, + SourceT, + ArrayT, + IteratorT, + ReverseT, + ElemT + >, + ElemT, > implements - IContainer.Iterator, - IRandomAccessIterator + IContainer.Iterator, + IRandomAccessIterator { - private array_: ArrayT; - private index_: number; + private array_: ArrayT; + private index_: number; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * @param source Source container. - * @param index Index number. - */ - public constructor(array: ArrayT, index: number) { - this.array_ = array; - this.index_ = index; - } + /** + * Initializer Constructor. + * + * @param source Source container. + * @param index Index number. + */ + public constructor(array: ArrayT, index: number) { + this.array_ = array; + this.index_ = index; + } - /** - * @inheritDoc - */ - public abstract reverse(): ReverseT; + /** + * @inheritDoc + */ + public abstract reverse(): ReverseT; - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract source(): SourceT; + /** + * @inheritDoc + */ + public abstract source(): SourceT; - /** - * @internal - */ - public _Get_array(): ArrayT { - return this.array_; - } + /** + * @internal + */ + public _Get_array(): ArrayT { + return this.array_; + } - /** - * @inheritDoc - */ - public index(): number { - return this.index_; - } + /** + * @inheritDoc + */ + public index(): number { + return this.index_; + } - /** - * @inheritDoc - */ - public get value(): T { - return this.array_.at(this.index_); - } + /** + * @inheritDoc + */ + public get value(): T { + return this.array_.at(this.index_); + } - /** - * @inheritDoc - */ - public set value(val: T) { - this.array_.set(this.index_, val); - } + /** + * @inheritDoc + */ + public set value(val: T) { + this.array_.set(this.index_, val); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- MOVERS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public prev(): IteratorT { - return this.advance(-1); - } + /** + * @inheritDoc + */ + public prev(): IteratorT { + return this.advance(-1); + } - /** - * @inheritDoc - */ - public next(): IteratorT { - return this.advance(1); - } + /** + * @inheritDoc + */ + public next(): IteratorT { + return this.advance(1); + } - /** - * @inheritDoc - */ - public advance(n: number): IteratorT { - return this.array_.nth(this.index_ + n); - } + /** + * @inheritDoc + */ + public advance(n: number): IteratorT { + return this.array_.nth(this.index_ + n); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- COMPARES --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public equals(obj: IteratorT): boolean { - return equal_to(this.array_, obj.array_) && this.index_ === obj.index_; - } + /** + * @inheritDoc + */ + public equals(obj: IteratorT): boolean { + return equal_to(this.array_, obj.array_) && this.index_ === obj.index_; + } } diff --git a/src/internal/iterator/ArrayReverseIterator.ts b/src/internal/iterator/ArrayReverseIterator.ts index c416dfab..a42ec601 100644 --- a/src/internal/iterator/ArrayReverseIterator.ts +++ b/src/internal/iterator/ArrayReverseIterator.ts @@ -1,45 +1,45 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ import { IArrayContainer } from "../../base/container/IArrayContainer"; -import { ArrayReverseIteratorBase } from "./ArrayReverseIteratorBase"; - import { ArrayContainer } from "../container/linear/ArrayContainer"; import { ArrayIterator } from "./ArrayIterator"; +import { ArrayReverseIteratorBase } from "./ArrayReverseIteratorBase"; export class ArrayReverseIterator< - T, - SourceT extends ArrayContainer< - T, - SourceT, - SourceT, - ArrayIterator, - ArrayReverseIterator, - T - >, - > - extends ArrayReverseIteratorBase< - T, - SourceT, - SourceT, - ArrayIterator, - ArrayReverseIterator, - T + T, + SourceT extends ArrayContainer< + T, + SourceT, + SourceT, + ArrayIterator, + ArrayReverseIterator, + T + >, + > + extends ArrayReverseIteratorBase< + T, + SourceT, + SourceT, + ArrayIterator, + ArrayReverseIterator, + T + > + implements + IArrayContainer.ReverseIterator< + T, + SourceT, + ArrayIterator, + ArrayReverseIterator > - implements - IArrayContainer.ReverseIterator< - T, - SourceT, - ArrayIterator, - ArrayReverseIterator - > { - protected _Create_neighbor( - base: ArrayIterator, - ): ArrayReverseIterator { - return new ArrayReverseIterator(base); - } + protected _Create_neighbor( + base: ArrayIterator, + ): ArrayReverseIterator { + return new ArrayReverseIterator(base); + } } diff --git a/src/internal/iterator/ArrayReverseIteratorBase.ts b/src/internal/iterator/ArrayReverseIteratorBase.ts index 62c6ebf0..34d255ad 100644 --- a/src/internal/iterator/ArrayReverseIteratorBase.ts +++ b/src/internal/iterator/ArrayReverseIteratorBase.ts @@ -1,15 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { IRandomAccessIterator } from "../../iterator/IRandomAccessIterator"; -import { ReverseIterator } from "./ReverseIterator"; - import { IContainer } from "../../base/container/IContainer"; +import { IRandomAccessIterator } from "../../iterator/IRandomAccessIterator"; import { ArrayContainer } from "../container/linear/ArrayContainer"; import { ArrayIteratorBase } from "./ArrayIteratorBase"; +import { ReverseIterator } from "./ReverseIterator"; /** * Reverse iterator of Array Containers. @@ -17,68 +17,68 @@ import { ArrayIteratorBase } from "./ArrayIteratorBase"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class ArrayReverseIteratorBase< - T extends ElemT, - SourceT extends IContainer, - ArrayT extends ArrayContainer< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - ElemT - >, - IteratorT extends ArrayIteratorBase< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - ElemT - >, - ReverseT extends ArrayReverseIteratorBase< - T, - SourceT, - ArrayT, - IteratorT, - ReverseT, - ElemT - >, - ElemT, - > - extends ReverseIterator - implements IRandomAccessIterator + T extends ElemT, + SourceT extends IContainer, + ArrayT extends ArrayContainer< + T, + SourceT, + ArrayT, + IteratorT, + ReverseT, + ElemT + >, + IteratorT extends ArrayIteratorBase< + T, + SourceT, + ArrayT, + IteratorT, + ReverseT, + ElemT + >, + ReverseT extends ArrayReverseIteratorBase< + T, + SourceT, + ArrayT, + IteratorT, + ReverseT, + ElemT + >, + ElemT, + > + extends ReverseIterator + implements IRandomAccessIterator { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public advance(n: number): ReverseT { - return this._Create_neighbor(this.base().advance(-n)); - } + /** + * @inheritDoc + */ + public advance(n: number): ReverseT { + return this._Create_neighbor(this.base().advance(-n)); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public index(): number { - return this.base_.index(); - } + /** + * @inheritDoc + */ + public index(): number { + return this.base_.index(); + } - /** - * @inheritDoc - */ - public get value(): T { - return this.base_.value; - } + /** + * @inheritDoc + */ + public get value(): T { + return this.base_.value; + } - /** - * @inheritDoc - */ - public set value(val: T) { - this.base_.value = val; - } + /** + * @inheritDoc + */ + public set value(val: T) { + this.base_.value = val; + } } diff --git a/src/internal/iterator/InsertIteratorBase.ts b/src/internal/iterator/InsertIteratorBase.ts index e0fb30a3..9a320f8c 100644 --- a/src/internal/iterator/InsertIteratorBase.ts +++ b/src/internal/iterator/InsertIteratorBase.ts @@ -1,34 +1,34 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ import { IForwardIterator } from "../../iterator/IForwardIterator"; - import { Writeonly } from "../functional/Writeonly"; export abstract class InsertIteratorBase< - T, - This extends InsertIteratorBase, + T, + This extends InsertIteratorBase, > implements Writeonly> { - /** - * Set value. - * - * @param val The value to set. - */ - public abstract set value(val: T); + /** + * Set value. + * + * @param val The value to set. + */ + public abstract set value(val: T); - /** - * @inheritDoc - */ - public next(): This { - return this as any; - } + /** + * @inheritDoc + */ + public next(): This { + return this as any; + } - /** - * @inheritDoc - */ - public abstract equals(obj: This): boolean; + /** + * @inheritDoc + */ + public abstract equals(obj: This): boolean; } diff --git a/src/internal/iterator/ListIterator.ts b/src/internal/iterator/ListIterator.ts index 8d6e1d69..73ac9550 100644 --- a/src/internal/iterator/ListIterator.ts +++ b/src/internal/iterator/ListIterator.ts @@ -1,13 +1,13 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ import { IContainer } from "../../base/container/IContainer"; -import { ReverseIterator } from "./ReverseIterator"; - import { ErrorGenerator } from "../exception/ErrorGenerator"; +import { ReverseIterator } from "./ReverseIterator"; /** * Basic List Iterator. @@ -15,158 +15,137 @@ import { ErrorGenerator } from "../exception/ErrorGenerator"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class ListIterator< - T extends Elem, - SourceT extends IContainer, - IteratorT extends ListIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - ReverseIteratorT extends ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - Elem, + T extends Elem, + SourceT extends IContainer, + IteratorT extends ListIterator, + ReverseIteratorT extends ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + Elem, > implements - Readonly< - IContainer.Iterator - > + Readonly< + IContainer.Iterator + > { - private prev_: IteratorT; - private next_: IteratorT; - protected value_: T; + private prev_: IteratorT; + private next_: IteratorT; + protected value_: T; - /** - * @internal - */ - public erased_?: boolean; + /** + * @internal + */ + public erased_?: boolean; - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------------- */ - protected constructor(prev: IteratorT, next: IteratorT, value: T) { - this.prev_ = prev; - this.next_ = next; - this.value_ = value; - } + protected constructor(prev: IteratorT, next: IteratorT, value: T) { + this.prev_ = prev; + this.next_ = next; + this.value_ = value; + } - /** - * @inheritDoc - */ - public abstract reverse(): ReverseIteratorT; + /** + * @inheritDoc + */ + public abstract reverse(): ReverseIteratorT; - /** - * @internal - */ - public static _Set_prev< - T extends Elem, - SourceT extends IContainer< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - IteratorT extends ListIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - ReverseIteratorT extends ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - Elem, - >(it: IteratorT, prev: IteratorT): void { - it.prev_ = prev; - } + /** + * @internal + */ + public static _Set_prev< + T extends Elem, + SourceT extends IContainer, + IteratorT extends ListIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + ReverseIteratorT extends ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + Elem, + >(it: IteratorT, prev: IteratorT): void { + it.prev_ = prev; + } - /** - * @internal - */ - public static _Set_next< - T extends Elem, - SourceT extends IContainer< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - IteratorT extends ListIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - ReverseIteratorT extends ReverseIterator< - T, - SourceT, - IteratorT, - ReverseIteratorT, - Elem - >, - Elem, - >(it: IteratorT, next: IteratorT): void { - it.next_ = next; - } + /** + * @internal + */ + public static _Set_next< + T extends Elem, + SourceT extends IContainer, + IteratorT extends ListIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + ReverseIteratorT extends ReverseIterator< + T, + SourceT, + IteratorT, + ReverseIteratorT, + Elem + >, + Elem, + >(it: IteratorT, next: IteratorT): void { + it.next_ = next; + } - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- ACCESSORS --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public abstract source(): SourceT; + /** + * @inheritDoc + */ + public abstract source(): SourceT; - /** - * @inheritDoc - */ - public prev(): IteratorT { - return this.prev_; - } + /** + * @inheritDoc + */ + public prev(): IteratorT { + return this.prev_; + } - /** - * @inheritDoc - */ - public next(): IteratorT { - return this.next_; - } + /** + * @inheritDoc + */ + public next(): IteratorT { + return this.next_; + } - /** - * @inheritDoc - */ - public get value(): T { - this._Try_value(); - return this.value_; - } + /** + * @inheritDoc + */ + public get value(): T { + this._Try_value(); + return this.value_; + } - protected _Try_value(): void { - if ( - this.value_ === undefined && - this.equals(this.source().end()) === true - ) - throw ErrorGenerator.iterator_end_value(this.source()); - } + protected _Try_value(): void { + if (this.value_ === undefined && this.equals(this.source().end()) === true) + throw ErrorGenerator.iterator_end_value(this.source()); + } - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- COMPARISON --------------------------------------------------------------- */ - /** - * @inheritDoc - */ - public equals(obj: IteratorT): boolean { - return this === obj; - } + /** + * @inheritDoc + */ + public equals(obj: IteratorT): boolean { + return this === obj; + } } diff --git a/src/internal/iterator/ReverseIterator.ts b/src/internal/iterator/ReverseIterator.ts index f5e85a55..9a73ae58 100644 --- a/src/internal/iterator/ReverseIterator.ts +++ b/src/internal/iterator/ReverseIterator.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.base @@ -12,82 +13,82 @@ import { IContainer } from "../../base/container/IContainer"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class ReverseIterator< - T extends PElem, - Source extends IContainer, - Base extends IContainer.Iterator, - This extends ReverseIterator, - PElem = T, + T extends PElem, + Source extends IContainer, + Base extends IContainer.Iterator, + This extends ReverseIterator, + PElem = T, > implements IContainer.ReverseIterator { - protected base_: Base; + protected base_: Base; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * @param base The base iterator. - */ - public constructor(base: Base) { - this.base_ = base.prev(); - } + /** + * Initializer Constructor. + * + * @param base The base iterator. + */ + public constructor(base: Base) { + this.base_ = base.prev(); + } - // CREATE A NEW OBJECT WITH SAME (DERIVED) TYPE - protected abstract _Create_neighbor(base: Base): This; + // CREATE A NEW OBJECT WITH SAME (DERIVED) TYPE + protected abstract _Create_neighbor(base: Base): This; - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - /** - * Get source container. - * - * @return The source container. - */ - public source(): Source { - return this.base_.source(); - } + /** + * Get source container. + * + * @return The source container. + */ + public source(): Source { + return this.base_.source(); + } - /** - * @inheritDoc - */ - public base(): Base { - return this.base_.next(); - } + /** + * @inheritDoc + */ + public base(): Base { + return this.base_.next(); + } - /** - * @inheritDoc - */ - public get value(): T { - return this.base_.value; - } + /** + * @inheritDoc + */ + public get value(): T { + return this.base_.value; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- MOVERS --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public prev(): This { - // this.base().next() - return this._Create_neighbor(this.base().next()); - } + /** + * @inheritDoc + */ + public prev(): This { + // this.base().next() + return this._Create_neighbor(this.base().next()); + } - /** - * @inheritDoc - */ - public next(): This { - // this.base().prev() - return this._Create_neighbor(this.base_); - } + /** + * @inheritDoc + */ + public next(): This { + // this.base().prev() + return this._Create_neighbor(this.base_); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- COMPARES --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public equals(obj: This): boolean { - return this.base_.equals(obj.base_); - } + /** + * @inheritDoc + */ + public equals(obj: This): boolean { + return this.base_.equals(obj.base_); + } } diff --git a/src/internal/iterator/disposable/ForOfAdaptor.ts b/src/internal/iterator/disposable/ForOfAdaptor.ts index b344f53e..e17e8c4c 100644 --- a/src/internal/iterator/disposable/ForOfAdaptor.ts +++ b/src/internal/iterator/disposable/ForOfAdaptor.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -12,48 +13,48 @@ import { IForwardIterator } from "../../../iterator/IForwardIterator"; * @author Jeongho Nam - https://github.com/samchon */ export class ForOfAdaptor< - T, - InputIterator extends Readonly>, + T, + InputIterator extends Readonly>, > implements IterableIterator { - private it_: InputIterator; - private last_: InputIterator; + private it_: InputIterator; + private last_: InputIterator; - /** - * Initializer Constructor. - * - * @param first Input iteartor of the first position. - * @param last Input iterator of the last position. - */ - public constructor(first: InputIterator, last: InputIterator) { - this.it_ = first; - this.last_ = last; - } + /** + * Initializer Constructor. + * + * @param first Input iteartor of the first position. + * @param last Input iterator of the last position. + */ + public constructor(first: InputIterator, last: InputIterator) { + this.it_ = first; + this.last_ = last; + } - /** - * @inheritDoc - */ - public next(): IteratorResult { - if (this.it_.equals(this.last_)) - return { - done: true, - value: undefined!, - }; - else { - const it: InputIterator = this.it_; - this.it_ = this.it_.next(); + /** + * @inheritDoc + */ + public next(): IteratorResult { + if (this.it_.equals(this.last_)) + return { + done: true, + value: undefined!, + }; + else { + const it: InputIterator = this.it_; + this.it_ = this.it_.next(); - return { - done: false, - value: it.value, - }; - } + return { + done: false, + value: it.value, + }; } + } - /** - * @inheritDoc - */ - public [Symbol.iterator](): IterableIterator { - return this; - } + /** + * @inheritDoc + */ + public [Symbol.iterator](): IterableIterator { + return this; + } } diff --git a/src/internal/iterator/disposable/NativeArrayIterator.ts b/src/internal/iterator/disposable/NativeArrayIterator.ts index 51dc2a39..756d11f0 100644 --- a/src/internal/iterator/disposable/NativeArrayIterator.ts +++ b/src/internal/iterator/disposable/NativeArrayIterator.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -7,57 +8,57 @@ import { IForwardIterator } from "../../../iterator/IForwardIterator"; export class NativeArrayIterator - implements Readonly>> + implements Readonly>> { - private data_: Array; - private index_: number; + private data_: Array; + private index_: number; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - public constructor(data: Array, index: number) { - this.data_ = data; - this.index_ = index; - } + public constructor(data: Array, index: number) { + this.data_ = data; + this.index_ = index; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - public index(): number { - return this.index_; - } + public index(): number { + return this.index_; + } - public get value(): T { - return this.data_[this.index_]; - } + public get value(): T { + return this.data_[this.index_]; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- MOVERS --------------------------------------------------------- */ - public prev(): NativeArrayIterator { - --this.index_; - return this; - } - - public next(): NativeArrayIterator { - ++this.index_; - return this; - } - - public advance(n: number): NativeArrayIterator { - this.index_ += n; - return this; - } - - /* --------------------------------------------------------- + public prev(): NativeArrayIterator { + --this.index_; + return this; + } + + public next(): NativeArrayIterator { + ++this.index_; + return this; + } + + public advance(n: number): NativeArrayIterator { + this.index_ += n; + return this; + } + + /* --------------------------------------------------------- COMPARES --------------------------------------------------------- */ - public equals(obj: NativeArrayIterator): boolean { - return this.data_ === obj.data_ && this.index_ === obj.index_; - } - - public swap(obj: NativeArrayIterator): void { - [this.data_, obj.data_] = [obj.data_, this.data_]; - [this.index_, obj.index_] = [obj.index_, this.index_]; - } + public equals(obj: NativeArrayIterator): boolean { + return this.data_ === obj.data_ && this.index_ === obj.index_; + } + + public swap(obj: NativeArrayIterator): void { + [this.data_, obj.data_] = [obj.data_, this.data_]; + [this.index_, obj.index_] = [obj.index_, this.index_]; + } } diff --git a/src/internal/iterator/disposable/Repeater.ts b/src/internal/iterator/disposable/Repeater.ts index b89e8f62..7f6a6d2d 100644 --- a/src/internal/iterator/disposable/Repeater.ts +++ b/src/internal/iterator/disposable/Repeater.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -7,37 +8,37 @@ import { IForwardIterator } from "../../../iterator/IForwardIterator"; export class Repeater implements Readonly>> { - private index_: number; - private value_: T | undefined; + private index_: number; + private value_: T | undefined; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - public constructor(index: number, value?: T) { - this.index_ = index; - this.value_ = value; - } + public constructor(index: number, value?: T) { + this.index_ = index; + this.value_ = value; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - public index(): number { - return this.index_; - } + public index(): number { + return this.index_; + } - public get value(): T { - return this.value_!; - } + public get value(): T { + return this.value_!; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- MOVERS & COMPARE --------------------------------------------------------- */ - public next(): Repeater { - ++this.index_; - return this; - } + public next(): Repeater { + ++this.index_; + return this; + } - public equals(obj: Repeater): boolean { - return this.index_ === obj.index_; - } + public equals(obj: Repeater): boolean { + return this.index_ === obj.index_; + } } diff --git a/src/internal/numeric/Carlson.ts b/src/internal/numeric/Carlson.ts index 0f1051ff..2e4634c4 100644 --- a/src/internal/numeric/Carlson.ts +++ b/src/internal/numeric/Carlson.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -7,49 +8,49 @@ import { MathUtil } from "./MathUtil"; export namespace Carlson { - const INFINITY = 100 * 1000; - const SECTION = INFINITY; - - export function rf(x: number, y: number, z: number): number { - return ( - MathUtil.integral( - function (t: number): number { - let ret: number = t + x; - ret *= t + y; - ret *= t + z; - - return 1 / Math.sqrt(ret); - }, - 0, - INFINITY, - SECTION, - ) / 2 - ); - } - - export function rj(x: number, y: number, z: number, p: number): number { - return ( - MathUtil.integral( - function (t: number): number { - let ret: number = t + x; - ret *= t + y; - ret *= t + z; - ret = (t + p) * Math.sqrt(ret); - - return 1 / ret; - }, - 0, - INFINITY, - SECTION, - ) * 1.5 - ); - } - - export function rc(x: number, y: number) { - return rf(x, y, y); - } - - export function rd(x: number, y: number, z: number) { - return rj(x, y, z, z); - } + const INFINITY = 100 * 1000; + const SECTION = INFINITY; + + export function rf(x: number, y: number, z: number): number { + return ( + MathUtil.integral( + function (t: number): number { + let ret: number = t + x; + ret *= t + y; + ret *= t + z; + + return 1 / Math.sqrt(ret); + }, + 0, + INFINITY, + SECTION, + ) / 2 + ); + } + + export function rj(x: number, y: number, z: number, p: number): number { + return ( + MathUtil.integral( + function (t: number): number { + let ret: number = t + x; + ret *= t + y; + ret *= t + z; + ret = (t + p) * Math.sqrt(ret); + + return 1 / ret; + }, + 0, + INFINITY, + SECTION, + ) * 1.5 + ); + } + + export function rc(x: number, y: number) { + return rf(x, y, y); + } + + export function rd(x: number, y: number, z: number) { + return rj(x, y, z, z); + } } diff --git a/src/internal/numeric/MathUtil.ts b/src/internal/numeric/MathUtil.ts index 240272a2..defb92e4 100644 --- a/src/internal/numeric/MathUtil.ts +++ b/src/internal/numeric/MathUtil.ts @@ -5,42 +5,41 @@ */ //================================================================ export namespace MathUtil { - export function factorial(k: number): number { - if (FACTORIALS.length <= k) - for (let i: number = FACTORIALS.length; i <= k; ++i) - FACTORIALS.push(FACTORIALS[i - 1] * i); - - return FACTORIALS[k]; - } - - export function integral( - formula: (x: number) => number, - first: number, - last: number, - segment_count: number = 100 * 1000, - ): number { - if (first > last) [first, last] = [last, first]; - else if (first === last) return 0; - - const interval: number = (last - first) / segment_count; - let ret: number = 0.0; - - for (; first < last; first += interval) - ret += formula(first) * interval; - - return ret; - } - - export function sigma( - formula: (k: number) => number, - first: number, - last: number, - ): number { - let ret: number = 0.0; - for (; first <= last; ++first) ret += formula(first); - - return ret; - } - - const FACTORIALS: number[] = [1, 1]; + export function factorial(k: number): number { + if (FACTORIALS.length <= k) + for (let i: number = FACTORIALS.length; i <= k; ++i) + FACTORIALS.push(FACTORIALS[i - 1] * i); + + return FACTORIALS[k]; + } + + export function integral( + formula: (x: number) => number, + first: number, + last: number, + segment_count: number = 100 * 1000, + ): number { + if (first > last) [first, last] = [last, first]; + else if (first === last) return 0; + + const interval: number = (last - first) / segment_count; + let ret: number = 0.0; + + for (; first < last; first += interval) ret += formula(first) * interval; + + return ret; + } + + export function sigma( + formula: (k: number) => number, + first: number, + last: number, + ): number { + let ret: number = 0.0; + for (; first <= last; ++first) ret += formula(first); + + return ret; + } + + const FACTORIALS: number[] = [1, 1]; } diff --git a/src/internal/thread/AccessType.ts b/src/internal/thread/AccessType.ts index 003956a4..5bdbdfa7 100644 --- a/src/internal/thread/AccessType.ts +++ b/src/internal/thread/AccessType.ts @@ -5,6 +5,6 @@ */ //================================================================ export const enum AccessType { - WRITE, - READ, + WRITE, + READ, } diff --git a/src/internal/thread/LockType.ts b/src/internal/thread/LockType.ts index 036a8f47..2c6a7309 100644 --- a/src/internal/thread/LockType.ts +++ b/src/internal/thread/LockType.ts @@ -5,6 +5,6 @@ */ //================================================================ export const enum LockType { - HOLD, - KNOCK, + HOLD, + KNOCK, } diff --git a/src/internal/thread/SafeLock.ts b/src/internal/thread/SafeLock.ts index 18799e17..be2005c6 100644 --- a/src/internal/thread/SafeLock.ts +++ b/src/internal/thread/SafeLock.ts @@ -5,39 +5,39 @@ */ //================================================================ export namespace SafeLock { - export async function lock( - locker: () => Promise, - unlocker: () => Promise, - lambda: () => void | Promise, - ): Promise { - await locker(); - await _Process(unlocker, lambda); - } - - export async function try_lock( - locker: () => Promise, - unlocker: () => Promise, - lambda: () => void | Promise, - ): Promise { - if ((await locker()) === false) return false; + export async function lock( + locker: () => Promise, + unlocker: () => Promise, + lambda: () => void | Promise, + ): Promise { + await locker(); + await _Process(unlocker, lambda); + } - await _Process(unlocker, lambda); - return true; - } + export async function try_lock( + locker: () => Promise, + unlocker: () => Promise, + lambda: () => void | Promise, + ): Promise { + if ((await locker()) === false) return false; - async function _Process( - unlocker: () => Promise, - lambda: () => void | Promise, - ): Promise { - // PROCESS THE CRITICAL SECTION - try { - await lambda(); - } catch (error) { - await unlocker(); - throw error; - } + await _Process(unlocker, lambda); + return true; + } - // TERMINATE THE CRITICAL SECTION - await unlocker(); + async function _Process( + unlocker: () => Promise, + lambda: () => void | Promise, + ): Promise { + // PROCESS THE CRITICAL SECTION + try { + await lambda(); + } catch (error) { + await unlocker(); + throw error; } + + // TERMINATE THE CRITICAL SECTION + await unlocker(); + } } diff --git a/src/internal/tree/Color.ts b/src/internal/tree/Color.ts index eba94866..e4661a2a 100644 --- a/src/internal/tree/Color.ts +++ b/src/internal/tree/Color.ts @@ -5,6 +5,6 @@ */ //================================================================ export const enum Color { - BLACK, - RED, + BLACK, + RED, } diff --git a/src/internal/tree/MapTree.ts b/src/internal/tree/MapTree.ts index a9d5b6a9..6af0c6a6 100644 --- a/src/internal/tree/MapTree.ts +++ b/src/internal/tree/MapTree.ts @@ -1,140 +1,139 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { XTree } from "./XTree"; -import { XTreeNode } from "./XTreeNode"; - import { ITreeMap } from "../../base/container/ITreeMap"; -import { MapElementList } from "../container/associative/MapElementList"; - import { IPair } from "../../utility/IPair"; import { Pair } from "../../utility/Pair"; +import { MapElementList } from "../container/associative/MapElementList"; import { Comparator } from "../functional/Comparator"; +import { XTree } from "./XTree"; +import { XTreeNode } from "./XTreeNode"; export abstract class MapTree< + Key, + T, + Unique extends boolean, + Source extends ITreeMap< Key, T, - Unique extends boolean, - Source extends ITreeMap< - Key, - T, - Unique, - Source, - MapElementList.Iterator, - MapElementList.ReverseIterator - >, + Unique, + Source, + MapElementList.Iterator, + MapElementList.ReverseIterator + >, > extends XTree> { - private source_: Source; + private source_: Source; - private key_compare_: Comparator; - private key_eq_: Comparator; - private value_compare_: Comparator>; + private key_compare_: Comparator; + private key_eq_: Comparator; + private value_compare_: Comparator>; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - public constructor( - source: Source, - comp: Comparator, - it_comp: Comparator>, - ) { - super(it_comp); - this.source_ = source; - - this.key_compare_ = comp; - this.key_eq_ = function (x: Key, y: Key): boolean { - return !comp(x, y) && !comp(y, x); - }; - this.value_compare_ = function ( - x: IPair, - y: IPair, - ): boolean { - return comp(x.first, y.first); - }; - } - - /** - * @internal - */ - public static _Swap_source< - Key, - T, - Unique extends boolean, - Source extends ITreeMap< - Key, - T, - Unique, - Source, - MapElementList.Iterator, - MapElementList.ReverseIterator - >, - >( - x: MapTree, - y: MapTree, - ): void { - [x.source_, y.source_] = [y.source_, x.source_]; - } - - /* --------------------------------------------------------- + public constructor( + source: Source, + comp: Comparator, + it_comp: Comparator>, + ) { + super(it_comp); + this.source_ = source; + + this.key_compare_ = comp; + this.key_eq_ = function (x: Key, y: Key): boolean { + return !comp(x, y) && !comp(y, x); + }; + this.value_compare_ = function ( + x: IPair, + y: IPair, + ): boolean { + return comp(x.first, y.first); + }; + } + + /** + * @internal + */ + public static _Swap_source< + Key, + T, + Unique extends boolean, + Source extends ITreeMap< + Key, + T, + Unique, + Source, + MapElementList.Iterator, + MapElementList.ReverseIterator + >, + >( + x: MapTree, + y: MapTree, + ): void { + [x.source_, y.source_] = [y.source_, x.source_]; + } + + /* --------------------------------------------------------- FINDERS --------------------------------------------------------- */ - public get_by_key( - key: Key, - ): XTreeNode> | null { - const ret = this.nearest_by_key(key); - if (ret === null || !this.key_eq_(key, ret.value.first)) return null; - else return ret; - } - public abstract nearest_by_key( - key: Key, - ): XTreeNode> | null; - - public lower_bound( - key: Key, - ): MapElementList.Iterator { - const node: XTreeNode< - MapElementList.Iterator - > | null = this.nearest_by_key(key); - - if (node === null) return this.source().end(); - else if (this.key_comp()(node.value.first, key)) - // it < key - return node.value.next(); - else return node.value; - } - - public abstract upper_bound( - key: Key, - ): MapElementList.Iterator; - - public equal_range( - key: Key, - ): Pair< - MapElementList.Iterator, - MapElementList.Iterator - > { - return new Pair(this.lower_bound(key), this.upper_bound(key)); - } - - /* --------------------------------------------------------- + public get_by_key( + key: Key, + ): XTreeNode> | null { + const ret = this.nearest_by_key(key); + if (ret === null || !this.key_eq_(key, ret.value.first)) return null; + else return ret; + } + public abstract nearest_by_key( + key: Key, + ): XTreeNode> | null; + + public lower_bound( + key: Key, + ): MapElementList.Iterator { + const node: XTreeNode< + MapElementList.Iterator + > | null = this.nearest_by_key(key); + + if (node === null) return this.source().end(); + else if (this.key_comp()(node.value.first, key)) + // it < key + return node.value.next(); + else return node.value; + } + + public abstract upper_bound( + key: Key, + ): MapElementList.Iterator; + + public equal_range( + key: Key, + ): Pair< + MapElementList.Iterator, + MapElementList.Iterator + > { + return new Pair(this.lower_bound(key), this.upper_bound(key)); + } + + /* --------------------------------------------------------- ACCECSSORS --------------------------------------------------------- */ - public source(): Source { - return this.source_; - } + public source(): Source { + return this.source_; + } - public key_comp(): Comparator { - return this.key_compare_; - } + public key_comp(): Comparator { + return this.key_compare_; + } - public key_eq(): Comparator { - return this.key_eq_; - } + public key_eq(): Comparator { + return this.key_eq_; + } - public value_comp(): Comparator> { - return this.value_compare_; - } + public value_comp(): Comparator> { + return this.value_compare_; + } } diff --git a/src/internal/tree/MultiMapTree.ts b/src/internal/tree/MultiMapTree.ts index c769e0de..b4e7a5d8 100644 --- a/src/internal/tree/MultiMapTree.ts +++ b/src/internal/tree/MultiMapTree.ts @@ -1,125 +1,120 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { MapTree } from "./MapTree"; -import { XTreeNode } from "./XTreeNode"; - -import { MultiTreeMap } from "../container/associative/MultiTreeMap"; +import { get_uid } from "../../functional/uid"; import { MapElementList } from "../container/associative/MapElementList"; +import { MultiTreeMap } from "../container/associative/MultiTreeMap"; import { Comparator } from "../functional/Comparator"; - -import { get_uid } from "../../functional/uid"; +import { MapTree } from "./MapTree"; +import { XTreeNode } from "./XTreeNode"; export class MultiMapTree< + Key, + T, + Source extends MultiTreeMap< Key, T, - Source extends MultiTreeMap< - Key, - T, - Source, - MapElementList.Iterator, - MapElementList.ReverseIterator - >, + Source, + MapElementList.Iterator, + MapElementList.ReverseIterator + >, > extends MapTree { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - public constructor(source: Source, comp: Comparator) { - super( - source, - comp, - function ( - x: MapElementList.Iterator, - y: MapElementList.Iterator, - ): boolean { - const ret: boolean = comp(x.first, y.first); + public constructor(source: Source, comp: Comparator) { + super( + source, + comp, + function ( + x: MapElementList.Iterator, + y: MapElementList.Iterator, + ): boolean { + const ret: boolean = comp(x.first, y.first); - if (!ret && !comp(y.first, x.first)) - return get_uid(x) < get_uid(y); - else return ret; - }, - ); - } + if (!ret && !comp(y.first, x.first)) return get_uid(x) < get_uid(y); + else return ret; + }, + ); + } - public insert(val: MapElementList.Iterator): void { - // ISSUE UID BEFORE INSERTION - get_uid(val); - super.insert(val); - } + public insert(val: MapElementList.Iterator): void { + // ISSUE UID BEFORE INSERTION + get_uid(val); + super.insert(val); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- FINDERS --------------------------------------------------------- */ - private _Nearest_by_key( - key: Key, - equal_mover: ( - node: XTreeNode>, - ) => XTreeNode> | null, - ): XTreeNode> | null { - // NEED NOT TO ITERATE - if (this.root_ === null) return null; + private _Nearest_by_key( + key: Key, + equal_mover: ( + node: XTreeNode>, + ) => XTreeNode> | null, + ): XTreeNode> | null { + // NEED NOT TO ITERATE + if (this.root_ === null) return null; - //---- - // ITERATE - //---- - let ret: XTreeNode> = - this.root_; - let matched: XTreeNode< - MapElementList.Iterator - > | null = null; + //---- + // ITERATE + //---- + let ret: XTreeNode> = + this.root_; + let matched: XTreeNode< + MapElementList.Iterator + > | null = null; - while (true) { - const it: MapElementList.Iterator = - ret.value; - let my_node: XTreeNode< - MapElementList.Iterator - > | null = null; + while (true) { + const it: MapElementList.Iterator = ret.value; + let my_node: XTreeNode< + MapElementList.Iterator + > | null = null; - // COMPARE - if (this.key_comp()(key, it.first)) my_node = ret.left; - else if (this.key_comp()(it.first, key)) my_node = ret.right; - else { - // EQUAL, RESERVE THAT POINT - matched = ret; - my_node = equal_mover(ret); - } + // COMPARE + if (this.key_comp()(key, it.first)) my_node = ret.left; + else if (this.key_comp()(it.first, key)) my_node = ret.right; + else { + // EQUAL, RESERVE THAT POINT + matched = ret; + my_node = equal_mover(ret); + } - // ULTIL CHILD NODE EXISTS - if (my_node === null) break; - else ret = my_node; - } - - // RETURNS -> MATCHED OR NOT - return matched !== null ? matched : ret; + // ULTIL CHILD NODE EXISTS + if (my_node === null) break; + else ret = my_node; } - public nearest_by_key( - key: Key, - ): XTreeNode> | null { - return this._Nearest_by_key(key, function (node) { - return node.left; - }); - } + // RETURNS -> MATCHED OR NOT + return matched !== null ? matched : ret; + } - public upper_bound( - key: Key, - ): MapElementList.Iterator { - // FIND MATCHED NODE - const node: XTreeNode< - MapElementList.Iterator - > | null = this._Nearest_by_key(key, function (node) { - return node.right; - }); - if (node === null) - // NOTHING - return this.source().end(); + public nearest_by_key( + key: Key, + ): XTreeNode> | null { + return this._Nearest_by_key(key, function (node) { + return node.left; + }); + } - // MUST BE it.first > key - const it: MapElementList.Iterator = node.value; - if (this.key_comp()(key, it.first)) return it; - else return it.next(); - } + public upper_bound(key: Key): MapElementList.Iterator { + // FIND MATCHED NODE + const node: XTreeNode< + MapElementList.Iterator + > | null = this._Nearest_by_key(key, function (node) { + return node.right; + }); + if (node === null) + // NOTHING + return this.source().end(); + + // MUST BE it.first > key + const it: MapElementList.Iterator = node.value; + if (this.key_comp()(key, it.first)) return it; + else return it.next(); + } } diff --git a/src/internal/tree/MultiSetTree.ts b/src/internal/tree/MultiSetTree.ts index ed716d18..c01865fd 100644 --- a/src/internal/tree/MultiSetTree.ts +++ b/src/internal/tree/MultiSetTree.ts @@ -1,121 +1,115 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { SetTree } from "./SetTree"; -import { XTreeNode } from "./XTreeNode"; - +import { get_uid } from "../../functional/uid"; import { MultiTreeSet } from "../container/associative/MultiTreeSet"; import { SetElementList } from "../container/associative/SetElementList"; import { Comparator } from "../functional/Comparator"; - -import { get_uid } from "../../functional/uid"; +import { SetTree } from "./SetTree"; +import { XTreeNode } from "./XTreeNode"; export class MultiSetTree< + Key, + Source extends MultiTreeSet< Key, - Source extends MultiTreeSet< - Key, - Source, - SetElementList.Iterator, - SetElementList.ReverseIterator - >, + Source, + SetElementList.Iterator, + SetElementList.ReverseIterator + >, > extends SetTree { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - public constructor(source: Source, comp: Comparator) { - super( - source, - comp, - function ( - x: SetElementList.Iterator, - y: SetElementList.Iterator, - ): boolean { - const ret: boolean = comp(x.value, y.value); - if (!ret && !comp(y.value, x.value)) - return get_uid(x) < get_uid(y); - else return ret; - }, - ); - } + public constructor(source: Source, comp: Comparator) { + super( + source, + comp, + function ( + x: SetElementList.Iterator, + y: SetElementList.Iterator, + ): boolean { + const ret: boolean = comp(x.value, y.value); + if (!ret && !comp(y.value, x.value)) return get_uid(x) < get_uid(y); + else return ret; + }, + ); + } - public insert(val: SetElementList.Iterator): void { - // ISSUE UID BEFORE INSERTION - get_uid(val); - super.insert(val); - } + public insert(val: SetElementList.Iterator): void { + // ISSUE UID BEFORE INSERTION + get_uid(val); + super.insert(val); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- FINDERS --------------------------------------------------------- */ - private _Nearest_by_key( - key: Key, - equal_mover: ( - node: XTreeNode>, - ) => XTreeNode> | null, - ): XTreeNode> | null { - // NEED NOT TO ITERATE - if (this.root_ === null) return null; - - //---- - // ITERATE - //---- - let ret: XTreeNode> = - this.root_; - let matched: XTreeNode< - SetElementList.Iterator - > | null = null; + private _Nearest_by_key( + key: Key, + equal_mover: ( + node: XTreeNode>, + ) => XTreeNode> | null, + ): XTreeNode> | null { + // NEED NOT TO ITERATE + if (this.root_ === null) return null; - while (true) { - const candidate: SetElementList.Iterator = - ret.value; - let node: XTreeNode< - SetElementList.Iterator - > | null = null; + //---- + // ITERATE + //---- + let ret: XTreeNode> = + this.root_; + let matched: XTreeNode> | null = + null; - // COMPARE - if (this.key_comp()(key, candidate.value)) node = ret.left; - else if (this.key_comp()(candidate.value, key)) node = ret.right; - else { - // EQUAL, RESERVE THAT POINT - matched = ret; - node = equal_mover(ret); - } + while (true) { + const candidate: SetElementList.Iterator = ret.value; + let node: XTreeNode> | null = + null; - // ULTIL CHILD NODE EXISTS - if (node === null) break; - else ret = node; - } + // COMPARE + if (this.key_comp()(key, candidate.value)) node = ret.left; + else if (this.key_comp()(candidate.value, key)) node = ret.right; + else { + // EQUAL, RESERVE THAT POINT + matched = ret; + node = equal_mover(ret); + } - // RETURNS -> MATCHED OR NOT - return matched !== null ? matched : ret; + // ULTIL CHILD NODE EXISTS + if (node === null) break; + else ret = node; } - public nearest_by_key( - val: Key, - ): XTreeNode> | null { - return this._Nearest_by_key(val, function (node) { - return node.left; - }); - } + // RETURNS -> MATCHED OR NOT + return matched !== null ? matched : ret; + } - public upper_bound(val: Key): SetElementList.Iterator { - // FIND MATCHED NODE - const node: XTreeNode< - SetElementList.Iterator - > | null = this._Nearest_by_key(val, function (node) { - return node.right; - }); - if (node === null) - // NOTHING - return this.source().end(); + public nearest_by_key( + val: Key, + ): XTreeNode> | null { + return this._Nearest_by_key(val, function (node) { + return node.left; + }); + } - // MUST BE it.first > key - const it: SetElementList.Iterator = node.value; + public upper_bound(val: Key): SetElementList.Iterator { + // FIND MATCHED NODE + const node: XTreeNode> | null = + this._Nearest_by_key(val, function (node) { + return node.right; + }); + if (node === null) + // NOTHING + return this.source().end(); - if (this.key_comp()(val, it.value)) return it; - else return it.next(); - } + // MUST BE it.first > key + const it: SetElementList.Iterator = node.value; + + if (this.key_comp()(val, it.value)) return it; + else return it.next(); + } } diff --git a/src/internal/tree/SetTree.ts b/src/internal/tree/SetTree.ts index 0ce64592..ed5fe906 100644 --- a/src/internal/tree/SetTree.ts +++ b/src/internal/tree/SetTree.ts @@ -1,119 +1,117 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { XTree } from "./XTree"; - import { ITreeSet } from "../../base/container/ITreeSet"; -import { SetElementList } from "../container/associative/SetElementList"; -import { XTreeNode } from "./XTreeNode"; - import { Pair } from "../../utility/Pair"; +import { SetElementList } from "../container/associative/SetElementList"; import { Comparator } from "../functional/Comparator"; +import { XTree } from "./XTree"; +import { XTreeNode } from "./XTreeNode"; export abstract class SetTree< + Key, + Unique extends boolean, + Source extends ITreeSet< Key, - Unique extends boolean, - Source extends ITreeSet< - Key, - Unique, - Source, - SetElementList.Iterator, - SetElementList.ReverseIterator - >, + Unique, + Source, + SetElementList.Iterator, + SetElementList.ReverseIterator + >, > extends XTree> { - private source_: Source; + private source_: Source; - private key_comp_: Comparator; - private key_eq_: Comparator; + private key_comp_: Comparator; + private key_eq_: Comparator; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - public constructor( - set: Source, - comp: Comparator, - it_comp: Comparator>, - ) { - super(it_comp); - this.source_ = set; + public constructor( + set: Source, + comp: Comparator, + it_comp: Comparator>, + ) { + super(it_comp); + this.source_ = set; - this.key_comp_ = comp; - this.key_eq_ = (x, y) => !comp(x, y) && !comp(y, x); - } + this.key_comp_ = comp; + this.key_eq_ = (x, y) => !comp(x, y) && !comp(y, x); + } - /** - * @internal - */ - public static _Swap_source< - Key, - Unique extends boolean, - Source extends ITreeSet< - Key, - Unique, - Source, - SetElementList.Iterator, - SetElementList.ReverseIterator - >, - >(x: SetTree, y: SetTree): void { - [x.source_, y.source_] = [y.source_, x.source_]; - } + /** + * @internal + */ + public static _Swap_source< + Key, + Unique extends boolean, + Source extends ITreeSet< + Key, + Unique, + Source, + SetElementList.Iterator, + SetElementList.ReverseIterator + >, + >(x: SetTree, y: SetTree): void { + [x.source_, y.source_] = [y.source_, x.source_]; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- FINDERS --------------------------------------------------------- */ - public get_by_key( - val: Key, - ): XTreeNode> | null { - const ret = this.nearest_by_key(val); - if (ret === null || !this.key_eq_(val, ret.value.value)) return null; - else return ret; - } - public abstract nearest_by_key( - val: Key, - ): XTreeNode> | null; + public get_by_key( + val: Key, + ): XTreeNode> | null { + const ret = this.nearest_by_key(val); + if (ret === null || !this.key_eq_(val, ret.value.value)) return null; + else return ret; + } + public abstract nearest_by_key( + val: Key, + ): XTreeNode> | null; - public lower_bound(val: Key): SetElementList.Iterator { - const node: XTreeNode< - SetElementList.Iterator - > | null = this.nearest_by_key(val); + public lower_bound(val: Key): SetElementList.Iterator { + const node: XTreeNode> | null = + this.nearest_by_key(val); - if (node === null) return this.source_.end(); - else if (this.key_comp_(node.value.value, val)) - // it < key - return node.value.next(); - else return node.value; - } - public abstract upper_bound( - val: Key, - ): SetElementList.Iterator; + if (node === null) return this.source_.end(); + else if (this.key_comp_(node.value.value, val)) + // it < key + return node.value.next(); + else return node.value; + } + public abstract upper_bound( + val: Key, + ): SetElementList.Iterator; - public equal_range( - val: Key, - ): Pair< - SetElementList.Iterator, - SetElementList.Iterator - > { - return new Pair(this.lower_bound(val), this.upper_bound(val)); - } + public equal_range( + val: Key, + ): Pair< + SetElementList.Iterator, + SetElementList.Iterator + > { + return new Pair(this.lower_bound(val), this.upper_bound(val)); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ - public source(): Source { - return this.source_; - } + public source(): Source { + return this.source_; + } - public key_comp(): Comparator { - return this.key_comp_; - } - public key_eq(): Comparator { - return this.key_eq_; - } + public key_comp(): Comparator { + return this.key_comp_; + } + public key_eq(): Comparator { + return this.key_eq_; + } - public value_comp(): Comparator { - return this.key_comp_; - } + public value_comp(): Comparator { + return this.key_comp_; + } } diff --git a/src/internal/tree/UniqueMapTree.ts b/src/internal/tree/UniqueMapTree.ts index 5036f46f..e7c69eb4 100644 --- a/src/internal/tree/UniqueMapTree.ts +++ b/src/internal/tree/UniqueMapTree.ts @@ -1,81 +1,78 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { MapTree } from "./MapTree"; -import { XTreeNode } from "./XTreeNode"; - -import { UniqueTreeMap } from "../container/associative/UniqueTreeMap"; import { MapElementList } from "../container/associative/MapElementList"; +import { UniqueTreeMap } from "../container/associative/UniqueTreeMap"; import { Comparator } from "../functional/Comparator"; +import { MapTree } from "./MapTree"; +import { XTreeNode } from "./XTreeNode"; export class UniqueMapTree< + Key, + T, + Source extends UniqueTreeMap< Key, T, - Source extends UniqueTreeMap< - Key, - T, - Source, - MapElementList.Iterator, - MapElementList.ReverseIterator - >, + Source, + MapElementList.Iterator, + MapElementList.ReverseIterator + >, > extends MapTree { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - public constructor(source: Source, comp: Comparator) { - super(source, comp, (x, y) => comp(x.first, y.first)); - } + public constructor(source: Source, comp: Comparator) { + super(source, comp, (x, y) => comp(x.first, y.first)); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- FINDERS --------------------------------------------------------- */ - public nearest_by_key( - key: Key, - ): XTreeNode> | null { - // NEED NOT TO ITERATE - if (this.root_ === null) return null; + public nearest_by_key( + key: Key, + ): XTreeNode> | null { + // NEED NOT TO ITERATE + if (this.root_ === null) return null; - //---- - // ITERATE - //---- - let ret: XTreeNode< - MapElementList.Iterator - > | null = this.root_; + //---- + // ITERATE + //---- + let ret: XTreeNode> | null = + this.root_; - while (true) { - // UNTIL MEET THE MATCHED VALUE OR FINAL BRANCH - const it: MapElementList.Iterator = ret.value; - let my_node: XTreeNode< - MapElementList.Iterator - > | null = null; + while (true) { + // UNTIL MEET THE MATCHED VALUE OR FINAL BRANCH + const it: MapElementList.Iterator = ret.value; + let my_node: XTreeNode< + MapElementList.Iterator + > | null = null; - // COMPARE - if (this.key_comp()(key, it.first)) my_node = ret.left; - else if (this.key_comp()(it.first, key)) my_node = ret.right; - else return ret; // MATCHED VALUE + // COMPARE + if (this.key_comp()(key, it.first)) my_node = ret.left; + else if (this.key_comp()(it.first, key)) my_node = ret.right; + else return ret; // MATCHED VALUE - // FINAL BRANCH? OR KEEP GOING - if (my_node === null) break; - else ret = my_node; - } - return ret; // DIFFERENT NODE + // FINAL BRANCH? OR KEEP GOING + if (my_node === null) break; + else ret = my_node; } + return ret; // DIFFERENT NODE + } - public upper_bound( - key: Key, - ): MapElementList.Iterator { - // FIND MATCHED NODE - const node: XTreeNode< - MapElementList.Iterator - > | null = this.nearest_by_key(key); - if (node === null) return this.source().end(); + public upper_bound(key: Key): MapElementList.Iterator { + // FIND MATCHED NODE + const node: XTreeNode< + MapElementList.Iterator + > | null = this.nearest_by_key(key); + if (node === null) return this.source().end(); - // MUST BE it.first > key - const it: MapElementList.Iterator = node.value; - if (this.key_comp()(key, it.first)) return it; - else return it.next(); - } + // MUST BE it.first > key + const it: MapElementList.Iterator = node.value; + if (this.key_comp()(key, it.first)) return it; + else return it.next(); + } } diff --git a/src/internal/tree/UniqueSetTree.ts b/src/internal/tree/UniqueSetTree.ts index 5c2512cd..03915315 100644 --- a/src/internal/tree/UniqueSetTree.ts +++ b/src/internal/tree/UniqueSetTree.ts @@ -1,83 +1,81 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { SetTree } from "./SetTree"; - -import { XTreeNode } from "./XTreeNode"; -import { UniqueTreeSet } from "../container/associative/UniqueTreeSet"; import { SetElementList } from "../container/associative/SetElementList"; - +import { UniqueTreeSet } from "../container/associative/UniqueTreeSet"; import { Comparator } from "../functional/Comparator"; +import { SetTree } from "./SetTree"; +import { XTreeNode } from "./XTreeNode"; export class UniqueSetTree< + Key, + Source extends UniqueTreeSet< Key, - Source extends UniqueTreeSet< - Key, - Source, - SetElementList.Iterator, - SetElementList.ReverseIterator - >, + Source, + SetElementList.Iterator, + SetElementList.ReverseIterator + >, > extends SetTree { - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - public constructor(source: Source, comp: Comparator) { - super(source, comp, (x, y) => comp(x.value, y.value)); - } + public constructor(source: Source, comp: Comparator) { + super(source, comp, (x, y) => comp(x.value, y.value)); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- FINDERS --------------------------------------------------------- */ - public nearest_by_key( - val: Key, - ): XTreeNode> | null { - // NEED NOT TO ITERATE - if (this.root_ === null) return null; + public nearest_by_key( + val: Key, + ): XTreeNode> | null { + // NEED NOT TO ITERATE + if (this.root_ === null) return null; - //---- - // ITERATE - //---- - let ret: XTreeNode> | null = - this.root_; + //---- + // ITERATE + //---- + let ret: XTreeNode> | null = + this.root_; - while (true) { - // UNTIL MEET THE MATCHED VALUE OR FINAL BRANCH - const it: SetElementList.Iterator = ret.value; - let my_node: XTreeNode< - SetElementList.Iterator - > | null = null; + while (true) { + // UNTIL MEET THE MATCHED VALUE OR FINAL BRANCH + const it: SetElementList.Iterator = ret.value; + let my_node: XTreeNode< + SetElementList.Iterator + > | null = null; - // COMPARE - if (this.key_comp()(val, it.value)) my_node = ret.left; - else if (this.key_comp()(it.value, val)) my_node = ret.right; - else return ret; // MATCHED VALUE + // COMPARE + if (this.key_comp()(val, it.value)) my_node = ret.left; + else if (this.key_comp()(it.value, val)) my_node = ret.right; + else return ret; // MATCHED VALUE - // FINAL BRANCH? OR KEEP GOING - if (my_node === null) break; - else ret = my_node; - } - return ret; // DIFFERENT NODE + // FINAL BRANCH? OR KEEP GOING + if (my_node === null) break; + else ret = my_node; } + return ret; // DIFFERENT NODE + } - public upper_bound(val: Key): SetElementList.Iterator { - //-------- - // FIND MATCHED NODE - //-------- - const node: XTreeNode< - SetElementList.Iterator - > | null = this.nearest_by_key(val); - if (node === null) return this.source().end(); + public upper_bound(val: Key): SetElementList.Iterator { + //-------- + // FIND MATCHED NODE + //-------- + const node: XTreeNode> | null = + this.nearest_by_key(val); + if (node === null) return this.source().end(); - //-------- - // RETURN BRANCH - //-------- - const it: SetElementList.Iterator = node.value; + //-------- + // RETURN BRANCH + //-------- + const it: SetElementList.Iterator = node.value; - // MUST BE it.value > key - if (this.key_comp()(val, it.value)) return it; - else return it.next(); - } + // MUST BE it.value > key + if (this.key_comp()(val, it.value)) return it; + else return it.next(); + } } diff --git a/src/internal/tree/XTree.ts b/src/internal/tree/XTree.ts index bf924c8c..de7a37f9 100644 --- a/src/internal/tree/XTree.ts +++ b/src/internal/tree/XTree.ts @@ -1,13 +1,13 @@ //================================================================ + /** * @packageDocumentation * @module std.internal */ //================================================================ -import { XTreeNode } from "./XTreeNode"; -import { Color } from "./Color"; - import { Comparator } from "../functional/Comparator"; +import { Color } from "./Color"; +import { XTreeNode } from "./XTreeNode"; /** * Red-Black Tree @@ -17,76 +17,76 @@ import { Comparator } from "../functional/Comparator"; * @author Jeongho Nam - https://github.com/samchon */ export abstract class XTree { - protected root_: XTreeNode | null; + protected root_: XTreeNode | null; - private comp_: Comparator; - private equal_: Comparator; + private comp_: Comparator; + private equal_: Comparator; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - protected constructor(comp: Comparator) { - this.root_ = null; + protected constructor(comp: Comparator) { + this.root_ = null; - this.comp_ = comp; - this.equal_ = function (x: T, y: T): boolean { - return !comp(x, y) && !comp(y, x); - }; - } + this.comp_ = comp; + this.equal_ = function (x: T, y: T): boolean { + return !comp(x, y) && !comp(y, x); + }; + } - public clear(): void { - this.root_ = null; - } + public clear(): void { + this.root_ = null; + } - /* ========================================================= + /* ========================================================= ACCESSORS - GETTERS - COMPARISON ============================================================ GETTERS --------------------------------------------------------- */ - public root(): XTreeNode | null { - return this.root_; - } - - public get(val: T): XTreeNode | null { - const ret = this.nearest(val); - if (ret === null || !this.equal_(val, ret.value)) return null; - else return ret; + public root(): XTreeNode | null { + return this.root_; + } + + public get(val: T): XTreeNode | null { + const ret = this.nearest(val); + if (ret === null || !this.equal_(val, ret.value)) return null; + else return ret; + } + + public nearest(val: T): XTreeNode | null { + // NEED NOT TO ITERATE + if (this.root_ === null) return null; + + //---- + // ITERATE + //---- + let ret: XTreeNode | null = this.root_; + + while (true) { + // UNTIL MEET THE MATCHED VALUE OR FINAL BRANCH + let my_node: XTreeNode | null = null; + + // COMPARE + if (this.comp_(val, ret.value)) my_node = ret.left; + else if (this.comp_(ret.value, val)) my_node = ret.right; + else return ret; // MATCHED VALUE + + // FINAL BRANCH? OR KEEP GOING + if (my_node !== null) ret = my_node; + else break; } + return ret; // DIFFERENT NODE + } - public nearest(val: T): XTreeNode | null { - // NEED NOT TO ITERATE - if (this.root_ === null) return null; - - //---- - // ITERATE - //---- - let ret: XTreeNode | null = this.root_; - - while (true) { - // UNTIL MEET THE MATCHED VALUE OR FINAL BRANCH - let my_node: XTreeNode | null = null; - - // COMPARE - if (this.comp_(val, ret.value)) my_node = ret.left; - else if (this.comp_(ret.value, val)) my_node = ret.right; - else return ret; // MATCHED VALUE - - // FINAL BRANCH? OR KEEP GOING - if (my_node !== null) ret = my_node; - else break; - } - return ret; // DIFFERENT NODE - } + private _Fetch_maximum(node: XTreeNode): XTreeNode { + while (node.right !== null) node = node.right; - private _Fetch_maximum(node: XTreeNode): XTreeNode { - while (node.right !== null) node = node.right; + return node; + } - return node; - } - - /* ========================================================= + /* ========================================================= ELEMENTS I/O - INSERT - ERASE @@ -95,212 +95,212 @@ export abstract class XTree { ============================================================ INSERT --------------------------------------------------------- */ - public insert(val: T): void { - const parent = this.nearest(val); - const node = new XTreeNode(val, Color.RED); - - if (parent === null) this.root_ = node; - else { - node.parent = parent; + public insert(val: T): void { + const parent = this.nearest(val); + const node = new XTreeNode(val, Color.RED); - if (this.comp_(node.value, parent.value)) parent.left = node; - else parent.right = node; - } - - this._Insert_case1(node); - } - - private _Insert_case1(n: XTreeNode): void { - if (n.parent === null) n.color = Color.BLACK; - else this._Insert_case2(n); - } + if (parent === null) this.root_ = node; + else { + node.parent = parent; - private _Insert_case2(n: XTreeNode): void { - if (this._Fetch_color(n.parent) === Color.BLACK) return; - else this._Insert_case3(n); + if (this.comp_(node.value, parent.value)) parent.left = node; + else parent.right = node; } - private _Insert_case3(n: XTreeNode): void { - if (this._Fetch_color(n.uncle) === Color.RED) { - n.parent!.color = Color.BLACK; - n.uncle!.color = Color.BLACK; - n.grand!.color = Color.RED; - - this._Insert_case1(n.grand!); - } else this._Insert_case4(n); + this._Insert_case1(node); + } + + private _Insert_case1(n: XTreeNode): void { + if (n.parent === null) n.color = Color.BLACK; + else this._Insert_case2(n); + } + + private _Insert_case2(n: XTreeNode): void { + if (this._Fetch_color(n.parent) === Color.BLACK) return; + else this._Insert_case3(n); + } + + private _Insert_case3(n: XTreeNode): void { + if (this._Fetch_color(n.uncle) === Color.RED) { + n.parent!.color = Color.BLACK; + n.uncle!.color = Color.BLACK; + n.grand!.color = Color.RED; + + this._Insert_case1(n.grand!); + } else this._Insert_case4(n); + } + + private _Insert_case4(n: XTreeNode): void { + if (n === n.parent!.right && n.parent === n.grand!.left) { + this._Rotate_left(n.parent!); + n = n.left!; + } else if (n === n.parent!.left && n.parent === n.grand!.right) { + this._Rotate_right(n.parent!); + n = n.right!; } - private _Insert_case4(n: XTreeNode): void { - if (n === n.parent!.right && n.parent === n.grand!.left) { - this._Rotate_left(n.parent!); - n = n.left!; - } else if (n === n.parent!.left && n.parent === n.grand!.right) { - this._Rotate_right(n.parent!); - n = n.right!; - } + this._Insert_case5(n); + } - this._Insert_case5(n); - } + private _Insert_case5(n: XTreeNode): void { + n.parent!.color = Color.BLACK; + n.grand!.color = Color.RED; - private _Insert_case5(n: XTreeNode): void { - n.parent!.color = Color.BLACK; - n.grand!.color = Color.RED; + if (n === n.parent!.left && n.parent === n.grand!.left) + this._Rotate_right(n.grand!); + else this._Rotate_left(n.grand!); + } - if (n === n.parent!.left && n.parent === n.grand!.left) - this._Rotate_right(n.grand!); - else this._Rotate_left(n.grand!); - } - - /* --------------------------------------------------------- + /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ - public erase(val: T): void { - let node: XTreeNode | null = this.get(val); - if (node === null) return; // UNABLE TO FIND THE MATCHED NODE - - if (node.left !== null && node.right !== null) { - const pred: XTreeNode = this._Fetch_maximum(node.left); - - node.value = pred.value; - node = pred; - } - - const child = node.right === null ? node.left : node.right; - if (this._Fetch_color(node) === Color.BLACK) { - node.color = this._Fetch_color(child); - this._Erase_case1(node); - } - this._Replace_node(node, child); - - if (this._Fetch_color(this.root_) === Color.RED) - this.root_!.color = Color.BLACK; - } + public erase(val: T): void { + let node: XTreeNode | null = this.get(val); + if (node === null) return; // UNABLE TO FIND THE MATCHED NODE - private _Erase_case1(n: XTreeNode): void { - if (n.parent === null) return; - else this._Erase_case2(n); + if (node.left !== null && node.right !== null) { + const pred: XTreeNode = this._Fetch_maximum(node.left); + + node.value = pred.value; + node = pred; } - private _Erase_case2(n: XTreeNode): void { - if (this._Fetch_color(n.sibling) === Color.RED) { - n.parent!.color = Color.RED; - n.sibling!.color = Color.BLACK; + const child = node.right === null ? node.left : node.right; + if (this._Fetch_color(node) === Color.BLACK) { + node.color = this._Fetch_color(child); + this._Erase_case1(node); + } + this._Replace_node(node, child); - if (n === n.parent!.left) this._Rotate_left(n.parent!); - else this._Rotate_right(n.parent!); - } + if (this._Fetch_color(this.root_) === Color.RED) + this.root_!.color = Color.BLACK; + } - this._Erase_case3(n); - } + private _Erase_case1(n: XTreeNode): void { + if (n.parent === null) return; + else this._Erase_case2(n); + } - private _Erase_case3(n: XTreeNode): void { - if ( - this._Fetch_color(n.parent) === Color.BLACK && - this._Fetch_color(n.sibling) === Color.BLACK && - this._Fetch_color(n.sibling!.left) === Color.BLACK && - this._Fetch_color(n.sibling!.right) === Color.BLACK - ) { - n.sibling!.color = Color.RED; - this._Erase_case1(n.parent!); - } else this._Erase_case4(n); - } + private _Erase_case2(n: XTreeNode): void { + if (this._Fetch_color(n.sibling) === Color.RED) { + n.parent!.color = Color.RED; + n.sibling!.color = Color.BLACK; - private _Erase_case4(N: XTreeNode): void { - if ( - this._Fetch_color(N.parent) === Color.RED && - N.sibling !== null && - this._Fetch_color(N.sibling) === Color.BLACK && - this._Fetch_color(N.sibling.left) === Color.BLACK && - this._Fetch_color(N.sibling.right) === Color.BLACK - ) { - N.sibling.color = Color.RED; - N.parent!.color = Color.BLACK; - } else this._Erase_case5(N); + if (n === n.parent!.left) this._Rotate_left(n.parent!); + else this._Rotate_right(n.parent!); } - private _Erase_case5(n: XTreeNode): void { - if ( - n === n.parent!.left && - n.sibling !== null && - this._Fetch_color(n.sibling) === Color.BLACK && - this._Fetch_color(n.sibling.left) === Color.RED && - this._Fetch_color(n.sibling.right) === Color.BLACK - ) { - n.sibling.color = Color.RED; - n.sibling.left!.color = Color.BLACK; - - this._Rotate_right(n.sibling); - } else if ( - n === n.parent!.right && - n.sibling !== null && - this._Fetch_color(n.sibling) === Color.BLACK && - this._Fetch_color(n.sibling.left) === Color.BLACK && - this._Fetch_color(n.sibling.right) === Color.RED - ) { - n.sibling.color = Color.RED; - n.sibling.right!.color = Color.BLACK; - - this._Rotate_left(n.sibling); - } - this._Erase_case6(n); + this._Erase_case3(n); + } + + private _Erase_case3(n: XTreeNode): void { + if ( + this._Fetch_color(n.parent) === Color.BLACK && + this._Fetch_color(n.sibling) === Color.BLACK && + this._Fetch_color(n.sibling!.left) === Color.BLACK && + this._Fetch_color(n.sibling!.right) === Color.BLACK + ) { + n.sibling!.color = Color.RED; + this._Erase_case1(n.parent!); + } else this._Erase_case4(n); + } + + private _Erase_case4(N: XTreeNode): void { + if ( + this._Fetch_color(N.parent) === Color.RED && + N.sibling !== null && + this._Fetch_color(N.sibling) === Color.BLACK && + this._Fetch_color(N.sibling.left) === Color.BLACK && + this._Fetch_color(N.sibling.right) === Color.BLACK + ) { + N.sibling.color = Color.RED; + N.parent!.color = Color.BLACK; + } else this._Erase_case5(N); + } + + private _Erase_case5(n: XTreeNode): void { + if ( + n === n.parent!.left && + n.sibling !== null && + this._Fetch_color(n.sibling) === Color.BLACK && + this._Fetch_color(n.sibling.left) === Color.RED && + this._Fetch_color(n.sibling.right) === Color.BLACK + ) { + n.sibling.color = Color.RED; + n.sibling.left!.color = Color.BLACK; + + this._Rotate_right(n.sibling); + } else if ( + n === n.parent!.right && + n.sibling !== null && + this._Fetch_color(n.sibling) === Color.BLACK && + this._Fetch_color(n.sibling.left) === Color.BLACK && + this._Fetch_color(n.sibling.right) === Color.RED + ) { + n.sibling.color = Color.RED; + n.sibling.right!.color = Color.BLACK; + + this._Rotate_left(n.sibling); } - - private _Erase_case6(n: XTreeNode): void { - n.sibling!.color = this._Fetch_color(n.parent); - n.parent!.color = Color.BLACK; - - if (n === n.parent!.left) { - n.sibling!.right!.color = Color.BLACK; - this._Rotate_left(n.parent!); - } else { - n.sibling!.left!.color = Color.BLACK; - this._Rotate_right(n.parent!); - } + this._Erase_case6(n); + } + + private _Erase_case6(n: XTreeNode): void { + n.sibling!.color = this._Fetch_color(n.parent); + n.parent!.color = Color.BLACK; + + if (n === n.parent!.left) { + n.sibling!.right!.color = Color.BLACK; + this._Rotate_left(n.parent!); + } else { + n.sibling!.left!.color = Color.BLACK; + this._Rotate_right(n.parent!); } + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ROTATION --------------------------------------------------------- */ - private _Rotate_left(node: XTreeNode): void { - const right = node.right; - this._Replace_node(node, right); - - node.right = right!.left; - if (right!.left !== null) right!.left!.parent = node; - - right!.left = node; - node.parent = right; + private _Rotate_left(node: XTreeNode): void { + const right = node.right; + this._Replace_node(node, right); + + node.right = right!.left; + if (right!.left !== null) right!.left!.parent = node; + + right!.left = node; + node.parent = right; + } + + private _Rotate_right(node: XTreeNode): void { + const left = node.left; + this._Replace_node(node, left); + + node.left = left!.right; + if (left!.right !== null) left!.right!.parent = node; + + left!.right = node; + node.parent = left; + } + + private _Replace_node( + oldNode: XTreeNode, + newNode: XTreeNode | null, + ): void { + if (oldNode.parent === null) this.root_ = newNode; + else { + if (oldNode === oldNode.parent.left) oldNode.parent.left = newNode; + else oldNode.parent.right = newNode; } - private _Rotate_right(node: XTreeNode): void { - const left = node.left; - this._Replace_node(node, left); + if (newNode !== null) newNode.parent = oldNode.parent; + } - node.left = left!.right; - if (left!.right !== null) left!.right!.parent = node; - - left!.right = node; - node.parent = left; - } - - private _Replace_node( - oldNode: XTreeNode, - newNode: XTreeNode | null, - ): void { - if (oldNode.parent === null) this.root_ = newNode; - else { - if (oldNode === oldNode.parent.left) oldNode.parent.left = newNode; - else oldNode.parent.right = newNode; - } - - if (newNode !== null) newNode.parent = oldNode.parent; - } - - /* --------------------------------------------------------- + /* --------------------------------------------------------- COLOR --------------------------------------------------------- */ - private _Fetch_color(node: XTreeNode | null): Color { - if (node === null) return Color.BLACK; - else return node.color; - } + private _Fetch_color(node: XTreeNode | null): Color { + if (node === null) return Color.BLACK; + else return node.color; + } } diff --git a/src/internal/tree/XTreeNode.ts b/src/internal/tree/XTreeNode.ts index e1d82e92..208e9b62 100644 --- a/src/internal/tree/XTreeNode.ts +++ b/src/internal/tree/XTreeNode.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std.internal @@ -12,35 +13,35 @@ import { Color } from "./Color"; * @author Jeongho Nam - https://github.com/samchon */ export class XTreeNode { - public parent: XTreeNode | null; - public left: XTreeNode | null; - public right: XTreeNode | null; + public parent: XTreeNode | null; + public left: XTreeNode | null; + public right: XTreeNode | null; - public value: T; - public color: Color; + public value: T; + public color: Color; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - public constructor(value: T, color: Color) { - this.value = value; - this.color = color; - - this.parent = null; - this.left = null; - this.right = null; - } - - public get grand(): XTreeNode | null { - return this.parent!.parent; - } - - public get sibling(): XTreeNode | null { - if (this === this.parent!.left) return this.parent!.right; - else return this.parent!.left; - } - - public get uncle(): XTreeNode | null { - return this.parent!.sibling; - } + public constructor(value: T, color: Color) { + this.value = value; + this.color = color; + + this.parent = null; + this.left = null; + this.right = null; + } + + public get grand(): XTreeNode | null { + return this.parent!.parent; + } + + public get sibling(): XTreeNode | null { + if (this === this.parent!.left) return this.parent!.right; + else return this.parent!.left; + } + + public get uncle(): XTreeNode | null { + return this.parent!.sibling; + } } diff --git a/src/iterator/BackInsertIterator.ts b/src/iterator/BackInsertIterator.ts index ad30bb58..4b84ee78 100644 --- a/src/iterator/BackInsertIterator.ts +++ b/src/iterator/BackInsertIterator.ts @@ -1,13 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { InsertIteratorBase } from "../internal/iterator/InsertIteratorBase"; -import { IPushBack } from "../internal/container/partial/IPushBack"; import { Vector } from "../container/Vector"; import { equal_to } from "../functional/comparators"; +import { IPushBack } from "../internal/container/partial/IPushBack"; +import { InsertIteratorBase } from "../internal/iterator/InsertIteratorBase"; /** * Back insert iterator. @@ -15,54 +16,54 @@ import { equal_to } from "../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export class BackInsertIterator< - Source extends IPushBack>, + Source extends IPushBack>, > extends InsertIteratorBase< - BackInsertIterator.ValueType, - BackInsertIterator + BackInsertIterator.ValueType, + BackInsertIterator > { - private source_: Source; + private source_: Source; - /* --------------------------------------------------------- + /* --------------------------------------------------------- METHODS --------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * @param source The source container. - */ - public constructor(source: Source) { - super(); - this.source_ = source; - } + /** + * Initializer Constructor. + * + * @param source The source container. + */ + public constructor(source: Source) { + super(); + this.source_ = source; + } - /** - * @inheritDoc - */ - public set value(val: BackInsertIterator.ValueType) { - this.source_.push_back(val); - } + /** + * @inheritDoc + */ + public set value(val: BackInsertIterator.ValueType) { + this.source_.push_back(val); + } - /** - * @inheritDoc - */ - public equals(obj: BackInsertIterator): boolean { - return equal_to(this.source_, obj.source_); - } + /** + * @inheritDoc + */ + public equals(obj: BackInsertIterator): boolean { + return equal_to(this.source_, obj.source_); + } } /** * */ export namespace BackInsertIterator { - /** - * Deduct value type. - */ - export type ValueType> = - Source extends IPushBack ? T : unknown; + /** + * Deduct value type. + */ + export type ValueType> = + Source extends IPushBack ? T : unknown; - /** - * Deduct source type. - */ - export type SourceType | IPushBack> = - Source extends Array ? Vector : Source; + /** + * Deduct source type. + */ + export type SourceType | IPushBack> = + Source extends Array ? Vector : Source; } diff --git a/src/iterator/FrontInsertIterator.ts b/src/iterator/FrontInsertIterator.ts index a99d7c18..ff93de1e 100644 --- a/src/iterator/FrontInsertIterator.ts +++ b/src/iterator/FrontInsertIterator.ts @@ -1,13 +1,13 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { InsertIteratorBase } from "../internal/iterator/InsertIteratorBase"; - -import { IPushFront } from "../internal/container/partial/IPushFront"; import { equal_to } from "../functional/comparators"; +import { IPushFront } from "../internal/container/partial/IPushFront"; +import { InsertIteratorBase } from "../internal/iterator/InsertIteratorBase"; /** * Front insert iterator. @@ -15,44 +15,44 @@ import { equal_to } from "../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export class FrontInsertIterator< - Source extends IPushFront>, + Source extends IPushFront>, > extends InsertIteratorBase< - FrontInsertIterator.ValueType, - FrontInsertIterator + FrontInsertIterator.ValueType, + FrontInsertIterator > { - private source_: Source; + private source_: Source; - /* --------------------------------------------------------- + /* --------------------------------------------------------- METHODS --------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * @param source The source container. - */ - public constructor(source: Source) { - super(); - this.source_ = source; - } + /** + * Initializer Constructor. + * + * @param source The source container. + */ + public constructor(source: Source) { + super(); + this.source_ = source; + } - /** - * @inheritDoc - */ - public set value(val: FrontInsertIterator.ValueType) { - this.source_.push_front(val); - } + /** + * @inheritDoc + */ + public set value(val: FrontInsertIterator.ValueType) { + this.source_.push_front(val); + } - /** - * @inheritDoc - */ - public equals(obj: FrontInsertIterator): boolean { - return equal_to(this.source_, obj.source_); - } + /** + * @inheritDoc + */ + public equals(obj: FrontInsertIterator): boolean { + return equal_to(this.source_, obj.source_); + } } export namespace FrontInsertIterator { - /** - * Deduct value type. - */ - export type ValueType> = - Source extends IPushFront ? T : unknown; + /** + * Deduct value type. + */ + export type ValueType> = + Source extends IPushFront ? T : unknown; } diff --git a/src/iterator/IBidirectionalIterator.ts b/src/iterator/IBidirectionalIterator.ts index ff37bb18..89329a2e 100644 --- a/src/iterator/IBidirectionalIterator.ts +++ b/src/iterator/IBidirectionalIterator.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,16 +13,16 @@ import { IForwardIterator } from "./IForwardIterator"; * @author Jeongho Nam - https://github.com/samchon */ export interface IBidirectionalIterator< + T, + Iterator extends IBidirectionalIterator = IBidirectionalIterator< T, - Iterator extends IBidirectionalIterator< - T, - Iterator - > = IBidirectionalIterator, + any + >, > extends IForwardIterator { - /** - * Get previous iterator. - * - * @return The previous iterator. - */ - prev(): Iterator; + /** + * Get previous iterator. + * + * @return The previous iterator. + */ + prev(): Iterator; } diff --git a/src/iterator/IForwardIterator.ts b/src/iterator/IForwardIterator.ts index d830c9ac..e4a1dcaa 100644 --- a/src/iterator/IForwardIterator.ts +++ b/src/iterator/IForwardIterator.ts @@ -1,11 +1,12 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IPointer } from "../functional/IPointer"; import { IComparable } from "../functional/IComparable"; +import { IPointer } from "../functional/IPointer"; /** * Forward iterator. @@ -13,22 +14,22 @@ import { IComparable } from "../functional/IComparable"; * @author Jeongho Nam - https://github.com/samchon */ export interface IForwardIterator< - T, - Iterator extends IForwardIterator = IForwardIterator, + T, + Iterator extends IForwardIterator = IForwardIterator, > extends IPointer, - Pick, "equals"> { - /** - * Get next iterator. - * - * @return The next iterator. - */ - next(): Iterator; + Pick, "equals"> { + /** + * Get next iterator. + * + * @return The next iterator. + */ + next(): Iterator; - /** - * Test whether equal to other iterator. - * - * @param obj The iterator to compare. - * @return Whether equal or not. - */ - equals(obj: Iterator): boolean; + /** + * Test whether equal to other iterator. + * + * @param obj The iterator to compare. + * @return Whether equal or not. + */ + equals(obj: Iterator): boolean; } diff --git a/src/iterator/IRandomAccessIterator.ts b/src/iterator/IRandomAccessIterator.ts index 89e92296..24c07822 100644 --- a/src/iterator/IRandomAccessIterator.ts +++ b/src/iterator/IRandomAccessIterator.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,24 +13,24 @@ import { IBidirectionalIterator } from "./IBidirectionalIterator"; * @author Jeongho Nam - https://github.com/samchon */ export interface IRandomAccessIterator< + T, + Iterator extends IRandomAccessIterator = IRandomAccessIterator< T, - Iterator extends IRandomAccessIterator = IRandomAccessIterator< - T, - any - >, + any + >, > extends IBidirectionalIterator { - /** - * Get index. - * - * @return The index. - */ - index(): number; + /** + * Get index. + * + * @return The index. + */ + index(): number; - /** - * Advance iterator. - * - * @param n Step to advance. - * @return The advanced iterator. - */ - advance(n: number): Iterator; + /** + * Advance iterator. + * + * @param n Step to advance. + * @return The advanced iterator. + */ + advance(n: number): Iterator; } diff --git a/src/iterator/IReversableIterator.ts b/src/iterator/IReversableIterator.ts index 54cb5b51..98cf61ac 100644 --- a/src/iterator/IReversableIterator.ts +++ b/src/iterator/IReversableIterator.ts @@ -1,11 +1,11 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ import { IBidirectionalIterator } from "./IBidirectionalIterator"; - import { IReverseIterator } from "./IReverseIterator"; /** @@ -14,14 +14,14 @@ import { IReverseIterator } from "./IReverseIterator"; * @author Jeongho Nam - https://github.com/samchon */ export interface IReversableIterator< - T, - IteratorT extends IReversableIterator, - ReverseT extends IReverseIterator, + T, + IteratorT extends IReversableIterator, + ReverseT extends IReverseIterator, > extends IBidirectionalIterator { - /** - * Construct reverse iterator. - * - * @return The reverse iterator. - */ - reverse(): ReverseT; + /** + * Construct reverse iterator. + * + * @return The reverse iterator. + */ + reverse(): ReverseT; } diff --git a/src/iterator/IReverseIterator.ts b/src/iterator/IReverseIterator.ts index ed3570da..7f563794 100644 --- a/src/iterator/IReverseIterator.ts +++ b/src/iterator/IReverseIterator.ts @@ -1,11 +1,11 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ import { IBidirectionalIterator } from "./IBidirectionalIterator"; - import { IReversableIterator } from "./IReversableIterator"; /** @@ -14,14 +14,14 @@ import { IReversableIterator } from "./IReversableIterator"; * @author Jeongho Nam - https://github.com/samchon */ export interface IReverseIterator< - T, - Base extends IReversableIterator, - This extends IReverseIterator, + T, + Base extends IReversableIterator, + This extends IReverseIterator, > extends IBidirectionalIterator { - /** - * Get base iterator. - * - * @return The base iterator. - */ - base(): Base; + /** + * Get base iterator. + * + * @return The base iterator. + */ + base(): Base; } diff --git a/src/iterator/InsertIterator.ts b/src/iterator/InsertIterator.ts index 59b887d2..94e9bb52 100644 --- a/src/iterator/InsertIterator.ts +++ b/src/iterator/InsertIterator.ts @@ -1,16 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { InsertIteratorBase } from "../internal/iterator/InsertIteratorBase"; - -import { IForwardIterator } from "./IForwardIterator"; import { IPointer } from "../functional/IPointer"; -import { IInsert } from "../internal/container/partial/IInsert"; - import { equal_to } from "../functional/comparators"; +import { IInsert } from "../internal/container/partial/IInsert"; +import { InsertIteratorBase } from "../internal/iterator/InsertIteratorBase"; +import { IForwardIterator } from "./IForwardIterator"; /** * Insert iterator. @@ -18,43 +17,43 @@ import { equal_to } from "../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export class InsertIterator< - Container extends IInsert, - Iterator extends IForwardIterator, Iterator>, + Container extends IInsert, + Iterator extends IForwardIterator, Iterator>, > extends InsertIteratorBase< - IPointer.ValueType, - InsertIterator + IPointer.ValueType, + InsertIterator > { - private container_: Container; - private it_: Iterator; + private container_: Container; + private it_: Iterator; - /* --------------------------------------------------------- + /* --------------------------------------------------------- METHODS --------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * @param container Target container to insert. - * @param it Iterator to the position to insert. - */ - public constructor(container: Container, it: Iterator) { - super(); + /** + * Initializer Constructor. + * + * @param container Target container to insert. + * @param it Iterator to the position to insert. + */ + public constructor(container: Container, it: Iterator) { + super(); - this.container_ = container; - this.it_ = it; - } + this.container_ = container; + this.it_ = it; + } - /** - * @inheritDoc - */ - public set value(val: IPointer.ValueType) { - this.it_ = this.container_.insert(this.it_, val); - this.it_ = this.it_.next() as Iterator; - } + /** + * @inheritDoc + */ + public set value(val: IPointer.ValueType) { + this.it_ = this.container_.insert(this.it_, val); + this.it_ = this.it_.next() as Iterator; + } - /** - * @inheritDoc - */ - public equals(obj: InsertIterator): boolean { - return equal_to(this.it_, obj.it_); - } + /** + * @inheritDoc + */ + public equals(obj: InsertIterator): boolean { + return equal_to(this.it_, obj.it_); + } } diff --git a/src/iterator/factory.ts b/src/iterator/factory.ts index d3031473..f1242ef6 100644 --- a/src/iterator/factory.ts +++ b/src/iterator/factory.ts @@ -1,24 +1,23 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IBidirectionalContainer } from "../ranges/container/IBidirectionalContainer"; -import { IReversableIterator } from "./IReversableIterator"; -import { IReverseIterator } from "./IReverseIterator"; - +import { Vector } from "../container/Vector"; import { IPointer } from "../functional/IPointer"; -import { IForwardContainer } from "../ranges/container/IForwardContainer"; import { IInsert } from "../internal/container/partial/IInsert"; -import { IPushFront } from "../internal/container/partial/IPushFront"; import { IPushBack } from "../internal/container/partial/IPushBack"; - -import { InsertIterator } from "./InsertIterator"; -import { FrontInsertIterator } from "./FrontInsertIterator"; +import { IPushFront } from "../internal/container/partial/IPushFront"; +import { IBidirectionalContainer } from "../ranges/container/IBidirectionalContainer"; +import { IForwardContainer } from "../ranges/container/IForwardContainer"; import { BackInsertIterator } from "./BackInsertIterator"; +import { FrontInsertIterator } from "./FrontInsertIterator"; import { IForwardIterator } from "./IForwardIterator"; -import { Vector } from "../container/Vector"; +import { IReversableIterator } from "./IReversableIterator"; +import { IReverseIterator } from "./IReverseIterator"; +import { InsertIterator } from "./InsertIterator"; /* --------------------------------------------------------- ITERATORS @@ -32,12 +31,12 @@ import { Vector } from "../container/Vector"; * @return Iterator to the first element. */ export function begin | IForwardContainer>( - container: Container, + container: Container, ): IForwardContainer.IteratorType; export function begin(container: Array | Vector): Vector.Iterator { - if (container instanceof Array) container = Vector.wrap(container); - return container.begin(); + if (container instanceof Array) container = Vector.wrap(container); + return container.begin(); } /** @@ -47,12 +46,12 @@ export function begin(container: Array | Vector): Vector.Iterator { * @return Iterator to the end. */ export function end | IForwardContainer>( - container: Container, + container: Container, ): IForwardContainer.IteratorType; export function end(container: Array | Vector): Vector.Iterator { - if (container instanceof Array) container = Vector.wrap(container); - return container.end(); + if (container instanceof Array) container = Vector.wrap(container); + return container.end(); } /** @@ -62,14 +61,14 @@ export function end(container: Array | Vector): Vector.Iterator { * @return The reverse iterator to the first. */ export function rbegin< - Container extends Array | IBidirectionalContainer, + Container extends Array | IBidirectionalContainer, >(container: Container): IBidirectionalContainer.ReverseIteratorType; export function rbegin( - container: Array | Vector, + container: Array | Vector, ): Vector.ReverseIterator { - if (container instanceof Array) container = Vector.wrap(container); - return container.rbegin(); + if (container instanceof Array) container = Vector.wrap(container); + return container.rbegin(); } /** @@ -79,14 +78,14 @@ export function rbegin( * @return The reverse iterator to the end. */ export function rend< - Container extends Array | IBidirectionalContainer, + Container extends Array | IBidirectionalContainer, >(container: Container): IBidirectionalContainer.ReverseIteratorType; export function rend( - container: Array | Vector, + container: Array | Vector, ): Vector.ReverseIterator { - if (container instanceof Array) container = Vector.wrap(container); - return container.rend(); + if (container instanceof Array) container = Vector.wrap(container); + return container.rend(); } /** @@ -96,18 +95,18 @@ export function rend( * @return The reverse iterator object. */ export function make_reverse_iterator< - IteratorT extends IReversableIterator< - IPointer.ValueType, - IteratorT, - ReverseT - >, - ReverseT extends IReverseIterator< - IPointer.ValueType, - IteratorT, - ReverseT - >, + IteratorT extends IReversableIterator< + IPointer.ValueType, + IteratorT, + ReverseT + >, + ReverseT extends IReverseIterator< + IPointer.ValueType, + IteratorT, + ReverseT + >, >(it: IteratorT): ReverseT { - return it.reverse(); + return it.reverse(); } /* --------------------------------------------------------- @@ -121,10 +120,10 @@ export function make_reverse_iterator< * @return The {@link InsertIterator insert iterator} object. */ export function inserter< - Container extends IInsert, - Iterator extends IForwardIterator, Iterator>, + Container extends IInsert, + Iterator extends IForwardIterator, Iterator>, >(container: Container, it: Iterator): InsertIterator { - return new InsertIterator(container, it); + return new InsertIterator(container, it); } /** @@ -134,9 +133,9 @@ export function inserter< * @return The {@link FrontInsertIterator front insert iterator} object. */ export function front_inserter< - Source extends IPushFront>, + Source extends IPushFront>, >(source: Source): FrontInsertIterator { - return new FrontInsertIterator(source); + return new FrontInsertIterator(source); } /** @@ -146,12 +145,12 @@ export function front_inserter< * @return The {@link back insert iterator} object. */ export function back_inserter | IPushBack>( - source: Source, + source: Source, ): BackInsertIterator>; export function back_inserter( - source: Array | Vector, + source: Array | Vector, ): BackInsertIterator> { - if (source instanceof Array) source = Vector.wrap(source); - return new BackInsertIterator(source); + if (source instanceof Array) source = Vector.wrap(source); + return new BackInsertIterator(source); } diff --git a/src/iterator/global.ts b/src/iterator/global.ts index 71725ff0..174b969e 100644 --- a/src/iterator/global.ts +++ b/src/iterator/global.ts @@ -1,19 +1,17 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ +import { InvalidArgument } from "../exception/InvalidArgument"; import { IPointer } from "../functional/IPointer"; - -import { IForwardIterator } from "./IForwardIterator"; -import { IBidirectionalIterator } from "./IBidirectionalIterator"; -import { IRandomAccessIterator } from "./IRandomAccessIterator"; - import { IEmpty } from "../internal/container/partial/IEmpty"; import { ISize } from "../internal/container/partial/ISize"; - -import { InvalidArgument } from "../exception/InvalidArgument"; +import { IBidirectionalIterator } from "./IBidirectionalIterator"; +import { IForwardIterator } from "./IForwardIterator"; +import { IRandomAccessIterator } from "./IRandomAccessIterator"; /* ========================================================= GLOBAL FUNCTIONS @@ -30,8 +28,8 @@ import { InvalidArgument } from "../exception/InvalidArgument"; * @return Whether empty or not. */ export function empty(source: Array | IEmpty): boolean { - if (source instanceof Array) return source.length !== 0; - else return source.empty(); + if (source instanceof Array) return source.length !== 0; + else return source.empty(); } /** @@ -41,8 +39,8 @@ export function empty(source: Array | IEmpty): boolean { * @return The number of elements in the container. */ export function size(source: Array | ISize): number { - if (source instanceof Array) return source.length; - else return source.size(); + if (source instanceof Array) return source.length; + else return source.size(); } /** @@ -54,36 +52,35 @@ export function size(source: Array | ISize): number { * @return The distance. */ export function distance< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, >(first: InputIterator, last: InputIterator): number; export function distance< - InputIterator extends Readonly< - IRandomAccessIterator, InputIterator> - >, + InputIterator extends Readonly< + IRandomAccessIterator, InputIterator> + >, >(first: InputIterator, last: InputIterator): number { - if (first.index instanceof Function) - return _Distance_via_index(first, last); + if (first.index instanceof Function) return _Distance_via_index(first, last); - let ret: number = 0; - for (; !first.equals(last); first = first.next()) ++ret; + let ret: number = 0; + for (; !first.equals(last); first = first.next()) ++ret; - return ret; + return ret; } function _Distance_via_index< - RandomAccessIterator extends IRandomAccessIterator< - IPointer.ValueType, - RandomAccessIterator - >, + RandomAccessIterator extends IRandomAccessIterator< + IPointer.ValueType, + RandomAccessIterator + >, >(first: RandomAccessIterator, last: RandomAccessIterator): number { - const x: number = first.index(); - const y: number = last.index(); + const x: number = first.index(); + const y: number = last.index(); - if ((first as any).base instanceof Function) return x - y; - else return y - x; + if ((first as any).base instanceof Function) return x - y; + else return y - x; } /* --------------------------------------------------------- @@ -98,34 +95,34 @@ function _Distance_via_index< * @return The advanced iterator. */ export function advance< - InputIterator extends IForwardIterator< - IPointer.ValueType, - InputIterator - >, + InputIterator extends IForwardIterator< + IPointer.ValueType, + InputIterator + >, >(it: InputIterator, n: number): InputIterator; export function advance< - InputIterator extends IRandomAccessIterator< - IPointer.ValueType, - InputIterator - >, + InputIterator extends IRandomAccessIterator< + IPointer.ValueType, + InputIterator + >, >(it: InputIterator, n: number): InputIterator { - if (n === 0) return it; - else if (it.advance instanceof Function) return it.advance(n); - - let stepper: (it: InputIterator) => InputIterator; - if (n < 0) { - if (!(it.prev instanceof Function)) - throw new InvalidArgument( - "Error on std.advance(): parametric iterator is not a bi-directional iterator, thus advancing to negative direction is not possible.", - ); - - stepper = (it) => it.prev(); - n = -n; - } else stepper = (it) => it.next(); - - while (n-- > 0) it = stepper(it); - return it; + if (n === 0) return it; + else if (it.advance instanceof Function) return it.advance(n); + + let stepper: (it: InputIterator) => InputIterator; + if (n < 0) { + if (!(it.prev instanceof Function)) + throw new InvalidArgument( + "Error on std.advance(): parametric iterator is not a bi-directional iterator, thus advancing to negative direction is not possible.", + ); + + stepper = (it) => it.prev(); + n = -n; + } else stepper = (it) => it.next(); + + while (n-- > 0) it = stepper(it); + return it; } /** @@ -136,13 +133,13 @@ export function advance< * @return An iterator moved to prev *n* steps. */ export function prev< - BidirectionalIterator extends IBidirectionalIterator< - IPointer.ValueType, - BidirectionalIterator - >, + BidirectionalIterator extends IBidirectionalIterator< + IPointer.ValueType, + BidirectionalIterator + >, >(it: BidirectionalIterator, n: number = 1): BidirectionalIterator { - if (n === 1) return it.prev(); - else return advance(it, -n); + if (n === 1) return it.prev(); + else return advance(it, -n); } /** @@ -153,11 +150,11 @@ export function prev< * @return Iterator moved to next *n* steps. */ export function next< - ForwardIterator extends IForwardIterator< - IPointer.ValueType, - ForwardIterator - >, + ForwardIterator extends IForwardIterator< + IPointer.ValueType, + ForwardIterator + >, >(it: ForwardIterator, n: number = 1): ForwardIterator { - if (n === 1) return it.next(); - else return advance(it, n); + if (n === 1) return it.next(); + else return advance(it, n); } diff --git a/src/module.ts b/src/module.ts index af1ca834..964b72e0 100644 --- a/src/module.ts +++ b/src/module.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std diff --git a/src/numeric/IComputable.ts b/src/numeric/IComputable.ts index b530503e..0541213f 100644 --- a/src/numeric/IComputable.ts +++ b/src/numeric/IComputable.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -7,10 +8,10 @@ import { INegatable } from "./INegatable"; export interface IComputable extends INegatable { - plus(val: Param): Ret; - minus(val: Param): Ret; + plus(val: Param): Ret; + minus(val: Param): Ret; - multiplies(val: Param): Ret; - divides(val: Param): Ret; - modules(val: Param): Ret; + multiplies(val: Param): Ret; + divides(val: Param): Ret; + modules(val: Param): Ret; } diff --git a/src/numeric/INegatable.ts b/src/numeric/INegatable.ts index cfd61227..256bf9a3 100644 --- a/src/numeric/INegatable.ts +++ b/src/numeric/INegatable.ts @@ -5,5 +5,5 @@ */ //================================================================ export interface INegatable { - negate(): Ret; + negate(): Ret; } diff --git a/src/numeric/operations.ts b/src/numeric/operations.ts index 6996a6cc..79bbcbd3 100644 --- a/src/numeric/operations.ts +++ b/src/numeric/operations.ts @@ -1,319 +1,319 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IForwardIterator } from "../iterator/IForwardIterator"; +import { IPointer } from "../functional/IPointer"; import { General } from "../internal/functional/General"; import { Writeonly } from "../internal/functional/Writeonly"; - -import { plus, minus, multiplies } from "./operators"; -import { IPointer } from "../functional/IPointer"; +import { IForwardIterator } from "../iterator/IForwardIterator"; +import { minus, multiplies, plus } from "./operators"; /** * Greatest Common Divider. */ export function gcd(x: number, y: number): number { - y = y.valueOf(); // `Number` to `number` - while (y !== 0) [x, y] = [y, x % y]; + y = y.valueOf(); // `Number` to `number` + while (y !== 0) [x, y] = [y, x % y]; - return x; + return x; } /** * Least Common Multiple. */ export function lcm(x: number, y: number): number { - return (x * y) / gcd(x, y); + return (x * y) / gcd(x, y); } /* --------------------------------------------------------- COMMON ALGORITHMS --------------------------------------------------------- */ export function iota< - ForwardIterator extends General>, + ForwardIterator extends General>, >(first: ForwardIterator, last: ForwardIterator, value: number): void { - for (; !first.equals(last); first = first.next()) first.value = value++; + for (; !first.equals(last); first = first.next()) first.value = value++; } export function accumulate< - InputIterator extends General< - IForwardIterator, InputIterator> - >, + InputIterator extends General< + IForwardIterator, InputIterator> + >, >( - first: InputIterator, - last: InputIterator, - init: IPointer.ValueType, - op: Operator = plus, + first: InputIterator, + last: InputIterator, + init: IPointer.ValueType, + op: Operator = plus, ): IPointer.ValueType { - for (; !first.equals(last); first = first.next()) - init = op(init, first.value); + for (; !first.equals(last); first = first.next()) + init = op(init, first.value); - return init; + return init; } export function inner_product< - InputIterator1 extends General< - IForwardIterator, InputIterator1> - >, - InputIterator2 extends General< - IForwardIterator, InputIterator2> - >, + InputIterator1 extends General< + IForwardIterator, InputIterator1> + >, + InputIterator2 extends General< + IForwardIterator, InputIterator2> + >, >( - first1: InputIterator1, - last1: InputIterator1, - first2: InputIterator2, - value: IPointer.ValueType, - adder: Operator = plus, - multiplier: Operator = multiplies, + first1: InputIterator1, + last1: InputIterator1, + first2: InputIterator2, + value: IPointer.ValueType, + adder: Operator = plus, + multiplier: Operator = multiplies, ): IPointer.ValueType { - for (; !first1.equals(last1); first1 = first1.next()) { - value = adder(value, multiplier(first1.value, first2.value)); - first2 = first2.next(); - } - return value; + for (; !first1.equals(last1); first1 = first1.next()) { + value = adder(value, multiplier(first1.value, first2.value)); + first2 = first2.next(); + } + return value; } export function adjacent_difference< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - subtracter: Operator = minus, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + subtracter: Operator = minus, ): OutputIterator { - if (first.equals(last)) return output; + if (first.equals(last)) return output; - // INITIALIZE - let before: IPointer.ValueType; - [first, output, before] = _Initialize( - first, - output, - ); + // INITIALIZE + let before: IPointer.ValueType; + [first, output, before] = _Initialize( + first, + output, + ); - // COMPUTE OPERATIONS - for (; !first.equals(last); first = first.next()) { - output.value = subtracter(first.value, before); + // COMPUTE OPERATIONS + for (; !first.equals(last); first = first.next()) { + output.value = subtracter(first.value, before); - before = first.value; - output = output.next(); - } - return output; + before = first.value; + output = output.next(); + } + return output; } export function partial_sum< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - adder: Operator = plus, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + adder: Operator = plus, ): OutputIterator { - if (first.equals(last)) return output; + if (first.equals(last)) return output; - // INITIALIZE - let sum: IPointer.ValueType; - [first, output, sum] = _Initialize( - first, - output, - ); + // INITIALIZE + let sum: IPointer.ValueType; + [first, output, sum] = _Initialize( + first, + output, + ); - // COMPUTE OPERATIONS - for (; !first.equals(last); first = first.next()) { - sum = adder(sum, first.value); + // COMPUTE OPERATIONS + for (; !first.equals(last); first = first.next()) { + sum = adder(sum, first.value); - output.value = sum; - output = output.next(); - } - return output; + output.value = sum; + output = output.next(); + } + return output; } /* --------------------------------------------------------- PREFIX SUMS --------------------------------------------------------- */ export function inclusive_scan< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - adder: Operator = plus, - init?: IPointer.ValueType, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + adder: Operator = plus, + init?: IPointer.ValueType, ): OutputIterator { - return transform_inclusive_scan( - first, - last, - output, - adder, - (val) => val, - init, - ); + return transform_inclusive_scan( + first, + last, + output, + adder, + (val) => val, + init, + ); } export function exclusive_scan< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - init: IPointer.ValueType, - op: Operator = plus, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + init: IPointer.ValueType, + op: Operator = plus, ): OutputIterator { - return transform_exclusive_scan( - first, - last, - output, - init, - op, - (val) => val, - ); + return transform_exclusive_scan( + first, + last, + output, + init, + op, + (val) => val, + ); } export function transform_inclusive_scan< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - binary: Operator, - unary: Transformer, - init?: IPointer.ValueType, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + binary: Operator, + unary: Transformer, + init?: IPointer.ValueType, ): OutputIterator { - if (first.equals(last)) return output; + if (first.equals(last)) return output; - // INITIALIZE - let before: IPointer.ValueType; - [first, output, before] = _Transform_initialize(first, output, unary, init); + // INITIALIZE + let before: IPointer.ValueType; + [first, output, before] = _Transform_initialize(first, output, unary, init); - // COMPUTE OPERATIONS - for (; !first.equals(last); first = first.next()) { - before = binary(before, unary(first.value)); + // COMPUTE OPERATIONS + for (; !first.equals(last); first = first.next()) { + before = binary(before, unary(first.value)); - output.value = before; - output = output.next(); - } - return output; + output.value = before; + output = output.next(); + } + return output; } export function transform_exclusive_scan< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - last: InputIterator, - output: OutputIterator, - init: IPointer.ValueType, - binary: Operator, - unary: Transformer, + first: InputIterator, + last: InputIterator, + output: OutputIterator, + init: IPointer.ValueType, + binary: Operator, + unary: Transformer, ): OutputIterator { - if (first.equals(last)) return output; + if (first.equals(last)) return output; - // INITIALIZE - let x: IPointer.ValueType = unary(first.value); - let y: IPointer.ValueType; - [first, output, y] = _Transform_initialize(first, output, unary, init); + // INITIALIZE + let x: IPointer.ValueType = unary(first.value); + let y: IPointer.ValueType; + [first, output, y] = _Transform_initialize(first, output, unary, init); - // COMPUTE OPERATIONS - for (; !first.equals(last); first = first.next()) { - y = binary(x, y); - x = unary(first.value); + // COMPUTE OPERATIONS + for (; !first.equals(last); first = first.next()) { + y = binary(x, y); + x = unary(first.value); - output.value = y; - output = output.next(); - } - return output; + output.value = y; + output = output.next(); + } + return output; } /* --------------------------------------------------------- BACK-GROUNDS --------------------------------------------------------- */ type Operator< - Iterator1 extends Readonly< - IForwardIterator, Iterator1> - >, - Iterator2 extends Readonly< - IForwardIterator, Iterator2> - >, + Iterator1 extends Readonly< + IForwardIterator, Iterator1> + >, + Iterator2 extends Readonly< + IForwardIterator, Iterator2> + >, > = ( - x: IPointer.ValueType, - y: IPointer.ValueType, + x: IPointer.ValueType, + y: IPointer.ValueType, ) => IPointer.ValueType; type Transformer< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, > = ( - val: IPointer.ValueType, + val: IPointer.ValueType, ) => IPointer.ValueType; function _Initialize< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - output: OutputIterator, - init?: IPointer.ValueType, + first: InputIterator, + output: OutputIterator, + init?: IPointer.ValueType, ): [InputIterator, OutputIterator, IPointer.ValueType] { - return _Transform_initialize(first, output, (val) => val, init); + return _Transform_initialize(first, output, (val) => val, init); } function _Transform_initialize< - InputIterator extends Readonly< - IForwardIterator, InputIterator> - >, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + InputIterator extends Readonly< + IForwardIterator, InputIterator> + >, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - first: InputIterator, - output: OutputIterator, - unary: Transformer, - init?: IPointer.ValueType, + first: InputIterator, + output: OutputIterator, + unary: Transformer, + init?: IPointer.ValueType, ): [InputIterator, OutputIterator, IPointer.ValueType] { - // WRITE THE FIRST OR INITIAL VALUE - const ret: IPointer.ValueType = unary( - init === undefined ? first.value : init, - ); - output.value = ret; + // WRITE THE FIRST OR INITIAL VALUE + const ret: IPointer.ValueType = unary( + init === undefined ? first.value : init, + ); + output.value = ret; - // RETURNS WITH ADVANCES - return [first.next(), output.next(), ret]; + // RETURNS WITH ADVANCES + return [first.next(), output.next(), ret]; } diff --git a/src/numeric/operators.ts b/src/numeric/operators.ts index 8f5af9af..4a2650b4 100644 --- a/src/numeric/operators.ts +++ b/src/numeric/operators.ts @@ -1,71 +1,72 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { INegatable } from "./INegatable"; import { IComputable } from "./IComputable"; +import { INegatable } from "./INegatable"; type PlusParam = number | string | Pick, "plus">; type Param> = - | number - | Pick, Key>; + | number + | Pick, Key>; /* --------------------------------------------------------- PLUS --------------------------------------------------------- */ export function plus, Y = X, Ret = X>( - x: X, - y: Y, + x: X, + y: Y, ): Ret { - if ((x as Partial>).plus instanceof Function) - return (x as Partial>).plus!(y); - else return x + y; + if ((x as Partial>).plus instanceof Function) + return (x as Partial>).plus!(y); + else return x + y; } export function minus, Y = X, Ret = X>( - x: X, - y: Y, + x: X, + y: Y, ): Ret { - if ((x as Partial>).minus instanceof Function) - return (x as Partial>).minus!(y); - else return (x - y) as any; + if ((x as Partial>).minus instanceof Function) + return (x as Partial>).minus!(y); + else return (x - y) as any; } export function negate, Ret = X>(x: X): Ret { - if ((x as INegatable).negate instanceof Function) - return (x as INegatable).negate(); - else return -x; + if ((x as INegatable).negate instanceof Function) + return (x as INegatable).negate(); + else return -x; } /* --------------------------------------------------------- MULTIPLY --------------------------------------------------------- */ export function multiplies< - X extends Param, - Y = X, - Ret = X, + X extends Param, + Y = X, + Ret = X, >(x: X, y: Y): Ret { - if ((x as Partial>).multiplies instanceof Function) - return (x as Partial>).multiplies!(y); - else return (x * y); + if ((x as Partial>).multiplies instanceof Function) + return (x as Partial>).multiplies!(y); + else return (x * y); } export function divides, Y = X, Ret = X>( - x: X, - y: Y, + x: X, + y: Y, ): Ret { - if ((x as Partial>).divides instanceof Function) - return (x as Partial>).divides!(y); - else return (x / y); + if ((x as Partial>).divides instanceof Function) + return (x as Partial>).divides!(y); + else return (x / y); } export function modules, Y = X, Ret = X>( - x: X, - y: Y, + x: X, + y: Y, ): Ret { - if ((x as Partial>).modules instanceof Function) - return (x as Partial>).modules!(y); - else return (x % y); + if ((x as Partial>).modules instanceof Function) + return (x as Partial>).modules!(y); + else return (x % y); } diff --git a/src/numeric/special_math/bessels.ts b/src/numeric/special_math/bessels.ts index c0cf2c5f..8b5dc3ed 100644 --- a/src/numeric/special_math/bessels.ts +++ b/src/numeric/special_math/bessels.ts @@ -1,11 +1,12 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { MathUtil } from "../../internal/numeric/MathUtil"; import { InvalidArgument } from "../../exception/InvalidArgument"; +import { MathUtil } from "../../internal/numeric/MathUtil"; import { tgamma } from "./gamma"; const INFINITY = 100; // (1 / 30!) is nearby 0. @@ -23,19 +24,19 @@ const INFINITY = 100; // (1 / 30!) is nearby 0. * @reference https://en.wikipedia.org/wiki/Bessel_function#Bessel_functions_of_the_first_kind:_J.CE.B1 */ export function cyl_bessel_j(n: number, x: number): number { - // VALIDATION - if (x < 0 && Math.floor(n) !== n) - throw new InvalidArgument( - `Error on std.cyl_bessel_j(): n must be integer when x is negative -> (n = ${n}, x = ${x}).`, - ); - else if (x === 0 && n !== 0) - throw new InvalidArgument( - `Error on std.cyl_bessel_j(): n must be zero when x is zero -> (n = ${n}, x = ${x}).`, - ); - - // COMPUTATION - if (n === Math.floor(n)) return _J_int(n, x); - else return _J_positive(n, x); + // VALIDATION + if (x < 0 && Math.floor(n) !== n) + throw new InvalidArgument( + `Error on std.cyl_bessel_j(): n must be integer when x is negative -> (n = ${n}, x = ${x}).`, + ); + else if (x === 0 && n !== 0) + throw new InvalidArgument( + `Error on std.cyl_bessel_j(): n must be zero when x is zero -> (n = ${n}, x = ${x}).`, + ); + + // COMPUTATION + if (n === Math.floor(n)) return _J_int(n, x); + else return _J_positive(n, x); } /** @@ -44,36 +45,36 @@ export function cyl_bessel_j(n: number, x: number): number { * @reference https://en.wikipedia.org/wiki/Bessel_function#Bessel_functions_of_the_second_kind:_Y.CE.B1 */ export function cyl_neumann(v: number, x: number): number { - if (x <= 0) - throw new InvalidArgument( - `Error on std.cyl_neumann(): x must be greater than zero -> (x = ${x}).`, - ); + if (x <= 0) + throw new InvalidArgument( + `Error on std.cyl_neumann(): x must be greater than zero -> (x = ${x}).`, + ); - const numerator: number = - cyl_bessel_j(v, x) * Math.cos(v * Math.PI) - cyl_bessel_j(-v, x); - const denominator: number = Math.sin(v * Math.PI); + const numerator: number = + cyl_bessel_j(v, x) * Math.cos(v * Math.PI) - cyl_bessel_j(-v, x); + const denominator: number = Math.sin(v * Math.PI); - return numerator / denominator; + return numerator / denominator; } function _J_int(n: number, x: number): number { - if (n < 0) return Math.pow(-1, n) * _J_positive(-n, x); - else return _J_positive(n, x); + if (n < 0) return Math.pow(-1, n) * _J_positive(-n, x); + else return _J_positive(n, x); } function _J_positive(v: number, x: number): number { - const sigma: number = MathUtil.sigma( - function (k: number): number { - let ret: number = Math.pow(-1, k) * Math.pow(x / 2, v + 2 * k); - ret /= MathUtil.factorial(k) * tgamma(v + k + 1); - - return ret; - }, - 0, - INFINITY, - ); - - return sigma; + const sigma: number = MathUtil.sigma( + function (k: number): number { + let ret: number = Math.pow(-1, k) * Math.pow(x / 2, v + 2 * k); + ret /= MathUtil.factorial(k) * tgamma(v + k + 1); + + return ret; + }, + 0, + INFINITY, + ); + + return sigma; } /* --------------------------------------------------------------- @@ -85,7 +86,7 @@ function _J_positive(v: number, x: number): number { * @reference https://en.wikipedia.org/wiki/Bessel_function#Spherical_Bessel_functions:_jn.2C_yn */ export function sph_bessel(n: number, x: number): number { - return Math.sqrt(Math.PI / (2 * x)) * cyl_bessel_j(n + 0.5, x); + return Math.sqrt(Math.PI / (2 * x)) * cyl_bessel_j(n + 0.5, x); } /** @@ -94,10 +95,10 @@ export function sph_bessel(n: number, x: number): number { * @reference https://en.wikipedia.org/wiki/Bessel_function#Spherical_Bessel_functions:_jn.2C_yn */ export function sph_neumann(n: number, x: number): number { - let ret: number = Math.sqrt(Math.PI / (2 * x)); - ret *= cyl_neumann(n + 0.5, x); + let ret: number = Math.sqrt(Math.PI / (2 * x)); + ret *= cyl_neumann(n + 0.5, x); - return ret; + return ret; } /*================================================================ @@ -113,33 +114,32 @@ export function sph_neumann(n: number, x: number): number { * @reference https://en.wikipedia.org/wiki/Bessel_function#Modified_Bessel_functions:_I.CE.B1_.2C_K.CE.B1 */ export function cyl_bessel_i(n: number, x: number): number { - // VALIDATION - if (x < 0 && Math.floor(n) !== n) - throw new InvalidArgument( - `Error on std.cyl_bessel_i(): n must be integer when x is negative -> (n = ${n}, x = ${x}).`, - ); - else if (x === 0 && n !== 0) - throw new InvalidArgument( - `Error on std.cyl_bessel_i(): n must be zero when x is zero -> (n = ${n}, x = ${x}).`, - ); - - // COMPUTATION - if (n === 0.5) return Math.sqrt(2.0 / (Math.PI * x)) * Math.sinh(x); - else return _Bessel_i(n, x); + // VALIDATION + if (x < 0 && Math.floor(n) !== n) + throw new InvalidArgument( + `Error on std.cyl_bessel_i(): n must be integer when x is negative -> (n = ${n}, x = ${x}).`, + ); + else if (x === 0 && n !== 0) + throw new InvalidArgument( + `Error on std.cyl_bessel_i(): n must be zero when x is zero -> (n = ${n}, x = ${x}).`, + ); + + // COMPUTATION + if (n === 0.5) return Math.sqrt(2.0 / (Math.PI * x)) * Math.sinh(x); + else return _Bessel_i(n, x); } function _Bessel_i(v: number, x: number): number { - return MathUtil.sigma( - function (k: number): number { - const numerator: number = Math.pow(x / 2, v + 2 * k); - const denominator: number = - MathUtil.factorial(k) * tgamma(v + k + 1); - - return numerator / denominator; - }, - 0, - INFINITY, - ); + return MathUtil.sigma( + function (k: number): number { + const numerator: number = Math.pow(x / 2, v + 2 * k); + const denominator: number = MathUtil.factorial(k) * tgamma(v + k + 1); + + return numerator / denominator; + }, + 0, + INFINITY, + ); } /* --------------------------------------------------------------- @@ -151,18 +151,18 @@ function _Bessel_i(v: number, x: number): number { * @reference https://en.wikipedia.org/wiki/Bessel_function#Modified_Bessel_functions:_I.CE.B1_.2C_K.CE.B1 */ export function cyl_bessel_k(n: number, x: number): number { - if (x <= 0) - throw new InvalidArgument( - `Error on std.cyl_bessel_k(): requires x > 0 -> (x = ${x}).`, - ); + if (x <= 0) + throw new InvalidArgument( + `Error on std.cyl_bessel_k(): requires x > 0 -> (x = ${x}).`, + ); - return _Bessel_k(n, x); + return _Bessel_k(n, x); } function _Bessel_k(v: number, z: number): number { - let ret: number = Math.PI / 2; - ret *= cyl_bessel_i(-v, z) - cyl_bessel_i(v, z); - ret /= Math.sin(v * Math.PI); + let ret: number = Math.PI / 2; + ret *= cyl_bessel_i(-v, z) - cyl_bessel_i(v, z); + ret /= Math.sin(v * Math.PI); - return ret; + return ret; } diff --git a/src/numeric/special_math/beta.ts b/src/numeric/special_math/beta.ts index ae8e9753..07aeb0d8 100644 --- a/src/numeric/special_math/beta.ts +++ b/src/numeric/special_math/beta.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,5 +13,5 @@ import { tgamma } from "./gamma"; * @reference https://en.wikipedia.org/wiki/Beta_function */ export function beta(x: number, y: number): number { - return (tgamma(x) * tgamma(y)) / tgamma(x + y); + return (tgamma(x) * tgamma(y)) / tgamma(x + y); } diff --git a/src/numeric/special_math/ellints.ts b/src/numeric/special_math/ellints.ts index d48b7c55..1a97e714 100644 --- a/src/numeric/special_math/ellints.ts +++ b/src/numeric/special_math/ellints.ts @@ -1,11 +1,12 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { MathUtil } from "../../internal/numeric/MathUtil"; import { InvalidArgument } from "../../exception/InvalidArgument"; +import { MathUtil } from "../../internal/numeric/MathUtil"; /* --------------------------------------------------------------- FIRST @@ -16,11 +17,11 @@ import { InvalidArgument } from "../../exception/InvalidArgument"; * @reference https://en.wikipedia.org/wiki/Elliptic_integral#Complete_elliptic_integral_of_the_first_kind */ export function ellint_1(k: number, phi: number): number { - // FORMULA OF INTEGRAL - const formula = function (x: number): number { - return 1.0 / _Common_formula(k, x); - }; - return _Post_process("ellint_1", k, phi, formula); + // FORMULA OF INTEGRAL + const formula = function (x: number): number { + return 1.0 / _Common_formula(k, x); + }; + return _Post_process("ellint_1", k, phi, formula); } /** @@ -29,7 +30,7 @@ export function ellint_1(k: number, phi: number): number { * @reference https://en.wikipedia.org/wiki/Elliptic_integral#Elliptic_integral_of_the_first_kind */ export function comp_ellint_1(k: number): number { - return ellint_1(k, Math.PI / 2); + return ellint_1(k, Math.PI / 2); } /* --------------------------------------------------------------- @@ -41,10 +42,10 @@ export function comp_ellint_1(k: number): number { * @reference https://en.wikipedia.org/wiki/Elliptic_integral#Incomplete_elliptic_integral_of_the_second_kind */ export function ellint_2(k: number, phi: number): number { - const formula = function (x: number): number { - return _Common_formula(k, x); - }; - return _Post_process("ellint_2", k, phi, formula); + const formula = function (x: number): number { + return _Common_formula(k, x); + }; + return _Post_process("ellint_2", k, phi, formula); } /** @@ -53,7 +54,7 @@ export function ellint_2(k: number, phi: number): number { * @reference https://en.wikipedia.org/wiki/Elliptic_integral#Complete_elliptic_integral_of_the_second_kind */ export function comp_ellint_2(k: number): number { - return ellint_2(k, Math.PI / 2); + return ellint_2(k, Math.PI / 2); } /* --------------------------------------------------------------- @@ -65,14 +66,14 @@ export function comp_ellint_2(k: number): number { * @reference https://en.wikipedia.org/wiki/Elliptic_integral#Complete_elliptic_integral_of_the_third_kind */ export function ellint_3(k: number, v: number, phi: number): number { - // SPECIAL VALIDATIONS ONLY FOR SERIES-3 - const predicator: number = 1 / Math.pow(Math.sin(phi), 2); - if (v > predicator) - throw new InvalidArgument( - `Error on std.ellint_3(): must be v < (1 / sin^2(phi)) -> (v = ${v}, 1 / sin^2(phi) = ${predicator}).`, - ); + // SPECIAL VALIDATIONS ONLY FOR SERIES-3 + const predicator: number = 1 / Math.pow(Math.sin(phi), 2); + if (v > predicator) + throw new InvalidArgument( + `Error on std.ellint_3(): must be v < (1 / sin^2(phi)) -> (v = ${v}, 1 / sin^2(phi) = ${predicator}).`, + ); - return _Ellint_3(k, v, phi); + return _Ellint_3(k, v, phi); } /** @@ -81,37 +82,37 @@ export function ellint_3(k: number, v: number, phi: number): number { * @reference https://en.wikipedia.org/wiki/Elliptic_integral#Incomplete_elliptic_integral_of_the_third_kind */ export function comp_ellint_3(k: number, n: number): number { - return ellint_3(k, n, Math.PI / 2); + return ellint_3(k, n, Math.PI / 2); } function _Ellint_3(k: number, v: number, phi: number): number { - const formula = function (x: number): number { - let denominator: number = 1 - v * Math.pow(Math.sin(x), 2); - denominator *= _Common_formula(k, x); + const formula = function (x: number): number { + let denominator: number = 1 - v * Math.pow(Math.sin(x), 2); + denominator *= _Common_formula(k, x); - return 1.0 / denominator; - }; - return _Post_process("ellint_3", k, phi, formula); + return 1.0 / denominator; + }; + return _Post_process("ellint_3", k, phi, formula); } /* --------------------------------------------------------------- BACKGROUNDS --------------------------------------------------------------- */ function _Common_formula(k: number, x: number): number { - return Math.sqrt(1 - Math.pow(k * Math.sin(x), 2)); + return Math.sqrt(1 - Math.pow(k * Math.sin(x), 2)); } function _Post_process( - func: string, - k: number, - phi: number, - formula: (x: number) => number, + func: string, + k: number, + phi: number, + formula: (x: number) => number, ): number { - if (Math.abs(k) > 1) - throw new InvalidArgument( - `Error on std.${func}(): must be |k| <= 1 -> (k = ${k}).`, - ); + if (Math.abs(k) > 1) + throw new InvalidArgument( + `Error on std.${func}(): must be |k| <= 1 -> (k = ${k}).`, + ); - const area: number = MathUtil.integral(formula, 0, phi); - return phi < 0 ? -area : area; + const area: number = MathUtil.integral(formula, 0, phi); + return phi < 0 ? -area : area; } diff --git a/src/numeric/special_math/expint.ts b/src/numeric/special_math/expint.ts index b7fe836f..ee31041d 100644 --- a/src/numeric/special_math/expint.ts +++ b/src/numeric/special_math/expint.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -10,23 +11,23 @@ import { MathUtil } from "../../internal/numeric/MathUtil"; * Exponential integral. */ export function expint(x: number): number { - if (x === 0) return -Infinity; - else if (x < 0) return -_E1_G(-x); - else return _EI_Factorial(x); + if (x === 0) return -Infinity; + else if (x < 0) return -_E1_G(-x); + else return _EI_Factorial(x); } function _EI_Factorial(x: number): number { - return ( - EULER + - Math.log(Math.abs(x)) / Math.log(Math.E) + - MathUtil.sigma( - function (k: number): number { - return Math.pow(x, k) / (k * MathUtil.factorial(k)); - }, - 1, - MAX_K, - ) - ); + return ( + EULER + + Math.log(Math.abs(x)) / Math.log(Math.E) + + MathUtil.sigma( + function (k: number): number { + return Math.pow(x, k) / (k * MathUtil.factorial(k)); + }, + 1, + MAX_K, + ) + ); } /* --------------------------------------------------------------- @@ -63,27 +64,27 @@ function _EI_Factorial(x: number): number { BARRY APPROXIMATION --------------------------------------------------------------- */ function _E1_G(x: number): number { - const h: number = _Compute_h(x); + const h: number = _Compute_h(x); - let ret: number = G + (1 - G) * Math.pow(Math.E, -x / (1 - G)); - ret = Math.pow(Math.E, -x) / ret; + let ret: number = G + (1 - G) * Math.pow(Math.E, -x / (1 - G)); + ret = Math.pow(Math.E, -x) / ret; - let ln: number = 1 + G / x - (1 - G) / Math.pow(h + B * x, 2); - ln = Math.log(ln) / Math.log(Math.E); + let ln: number = 1 + G / x - (1 - G) / Math.pow(h + B * x, 2); + ln = Math.log(ln) / Math.log(Math.E); - return ret * ln; + return ret * ln; } function _Compute_h(x: number): number { - const q: number = _Compute_q(x); - const left: number = 1 / (1 + Math.pow(x, 1.5)); - const right: number = (H_INF * q) / (1 + q); + const q: number = _Compute_q(x); + const left: number = 1 / (1 + Math.pow(x, 1.5)); + const right: number = (H_INF * q) / (1 + q); - return left + right; + return left + right; } function _Compute_q(x: number): number { - return (20 / 47) * Math.pow(x, Math.sqrt(31 / 26)); + return (20 / 47) * Math.pow(x, Math.sqrt(31 / 26)); } const EULER = 0.5772156649015328606; @@ -91,4 +92,4 @@ const MAX_K = 150; const G = Math.pow(Math.E, -EULER); const B = Math.sqrt((2 * (1 - G)) / (G * (2 - G))); const H_INF = - ((1 - G) * (G * G - 6 * G + 12)) / (3 * G * Math.pow(2 - G, 2) * B); + ((1 - G) * (G * G - 6 * G + 12)) / (3 * G * Math.pow(2 - G, 2) * B); diff --git a/src/numeric/special_math/gamma.ts b/src/numeric/special_math/gamma.ts index 187a3236..5dfe6808 100644 --- a/src/numeric/special_math/gamma.ts +++ b/src/numeric/special_math/gamma.ts @@ -10,29 +10,29 @@ * @reference https://en.wikipedia.org/wiki/Gamma_function, https://rosettacode.org/wiki/Gamma_function#JavaScript */ export function tgamma(x: number): number { - if (x < 0.5) return Math.PI / (Math.sin(Math.PI * x) * tgamma(1 - x)); - /*else if (x >= 1 && x === Math.floor(x)) + if (x < 0.5) return Math.PI / (Math.sin(Math.PI * x) * tgamma(1 - x)); + /*else if (x >= 1 && x === Math.floor(x)) return base.MathUtil.factorial(x - 1);*/ - x -= 1; - let a: number = P[0]; - const t: number = x + G + 0.5; + x -= 1; + let a: number = P[0]; + const t: number = x + G + 0.5; - for (let i: number = 1; i < P.length; ++i) a += P[i] / (x + i); + for (let i: number = 1; i < P.length; ++i) a += P[i] / (x + i); - return Math.sqrt(2 * Math.PI) * Math.pow(t, x + 0.5) * Math.exp(-t) * a; + return Math.sqrt(2 * Math.PI) * Math.pow(t, x + 0.5) * Math.exp(-t) * a; } /** * Log gamma function. */ export function lgamma(x: number): number { - return Math.log(tgamma(x)); + return Math.log(tgamma(x)); } const P: number[] = [ - 0.99999999999980993, 676.5203681218851, -1259.1392167224028, - 771.32342877765313, -176.61502916214059, 12.507343278686905, - -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7, + 0.99999999999980993, 676.5203681218851, -1259.1392167224028, + 771.32342877765313, -176.61502916214059, 12.507343278686905, + -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7, ]; const G: number = 7; diff --git a/src/numeric/special_math/hermite.ts b/src/numeric/special_math/hermite.ts index e841a4b6..ae5048fe 100644 --- a/src/numeric/special_math/hermite.ts +++ b/src/numeric/special_math/hermite.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,28 +13,28 @@ import { InvalidArgument } from "../../exception/InvalidArgument"; * @reference https://en.wikipedia.org/wiki/Hermite_polynomials */ export function hermite(n: number, x: number): number { - // VALIDATE PARAMETER - if ((n = Math.floor(n)) < 0) - throw new InvalidArgument( - `Error on std.hermite(): n must be unsigned integer -> (n = ${n}).`, - ); + // VALIDATE PARAMETER + if ((n = Math.floor(n)) < 0) + throw new InvalidArgument( + `Error on std.hermite(): n must be unsigned integer -> (n = ${n}).`, + ); - // MEMORIZATION - const solutions: number[] = [1, 2 * x]; + // MEMORIZATION + const solutions: number[] = [1, 2 * x]; - // COMPUTE RETURN VALUE - return _Hermite(n, x, solutions); + // COMPUTE RETURN VALUE + return _Hermite(n, x, solutions); } function _Hermite(n: number, x: number, solutions: number[]): number { - if (solutions.length > n) return solutions[n]; + if (solutions.length > n) return solutions[n]; - const hn_1: number = _Hermite(n - 1, x, solutions); - const hn_2: number = _Hermite(n - 2, x, solutions); + const hn_1: number = _Hermite(n - 1, x, solutions); + const hn_2: number = _Hermite(n - 2, x, solutions); - let ret: number = x * hn_1 - (n - 1) * hn_2; - ret *= 2; + let ret: number = x * hn_1 - (n - 1) * hn_2; + ret *= 2; - solutions[n] = ret; - return ret; + solutions[n] = ret; + return ret; } diff --git a/src/numeric/special_math/laguerres.ts b/src/numeric/special_math/laguerres.ts index d9e38f6a..8c52e368 100644 --- a/src/numeric/special_math/laguerres.ts +++ b/src/numeric/special_math/laguerres.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,7 +13,7 @@ import { InvalidArgument } from "../../exception/InvalidArgument"; * @reference https://en.wikipedia.org/wiki/Laguerre_polynomials */ export function laguerre(n: number, x: number): number { - return assoc_laguerre(n, 0, x); + return assoc_laguerre(n, 0, x); } /** @@ -21,33 +22,33 @@ export function laguerre(n: number, x: number): number { * @reference https://en.wikipedia.org/wiki/Laguerre_polynomials#Generalized_Laguerre_polynomials */ export function assoc_laguerre(n: number, m: number, x: number): number { - // VALIDATE PARAMETERS - if ((n = Math.floor(n)) < 0 || (m = Math.floor(m)) < 0) - throw new InvalidArgument( - `Error on std.assoc_laguerre(): both n and m must be unsigned integer -> (n = ${n}, m = ${m}).`, - ); + // VALIDATE PARAMETERS + if ((n = Math.floor(n)) < 0 || (m = Math.floor(m)) < 0) + throw new InvalidArgument( + `Error on std.assoc_laguerre(): both n and m must be unsigned integer -> (n = ${n}, m = ${m}).`, + ); - // MEMORIZATION - const solutions: number[] = [1, -x + m + 1]; + // MEMORIZATION + const solutions: number[] = [1, -x + m + 1]; - // COMPUTE RETURN VALUE - return _Compute_assoc_laguerre(n, m, x, solutions); + // COMPUTE RETURN VALUE + return _Compute_assoc_laguerre(n, m, x, solutions); } function _Compute_assoc_laguerre( - n: number, - m: number, - x: number, - solutions: number[], + n: number, + m: number, + x: number, + solutions: number[], ): number { - if (solutions.length > n) return solutions[n]; + if (solutions.length > n) return solutions[n]; - const ln_1: number = _Compute_assoc_laguerre(n - 1, m, x, solutions); - const ln_2: number = _Compute_assoc_laguerre(n - 2, m, x, solutions); + const ln_1: number = _Compute_assoc_laguerre(n - 1, m, x, solutions); + const ln_2: number = _Compute_assoc_laguerre(n - 2, m, x, solutions); - let ret: number = (2 * n - 1 + m - x) * ln_1 - (n + m - 1) * ln_2; - ret = ret / n; + let ret: number = (2 * n - 1 + m - x) * ln_1 - (n + m - 1) * ln_2; + ret = ret / n; - solutions[n] = ret; - return ret; + solutions[n] = ret; + return ret; } diff --git a/src/numeric/special_math/legendres.ts b/src/numeric/special_math/legendres.ts index 04c0d185..14ebe798 100644 --- a/src/numeric/special_math/legendres.ts +++ b/src/numeric/special_math/legendres.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,7 +13,7 @@ import { InvalidArgument } from "../../exception/InvalidArgument"; * @reference http://en.cppreference.com/w/cpp/numeric/special_math/legendre */ export function legendre(n: number, x: number): number { - return assoc_legendre(n, 0, x); + return assoc_legendre(n, 0, x); } /** @@ -21,63 +22,61 @@ export function legendre(n: number, x: number): number { * @reference https://en.wikipedia.org/wiki/Associated_Legendre_polynomials */ export function assoc_legendre(n: number, m: number, x: number): number { - // VALIDATE PARAMETERS - if ((n = Math.floor(n)) < 0 || (m = Math.floor(m)) < 0) - throw new InvalidArgument( - `Error on std.assoc_legendre(): both n and m must be unsigned integer -> (n = ${n}, m = ${m}).`, - ); - else if (Math.abs(x) > 1) - throw new InvalidArgument( - `Error on std.assoc_legendre(): must be |x| <= 1 -> (x = ${x}).`, - ); + // VALIDATE PARAMETERS + if ((n = Math.floor(n)) < 0 || (m = Math.floor(m)) < 0) + throw new InvalidArgument( + `Error on std.assoc_legendre(): both n and m must be unsigned integer -> (n = ${n}, m = ${m}).`, + ); + else if (Math.abs(x) > 1) + throw new InvalidArgument( + `Error on std.assoc_legendre(): must be |x| <= 1 -> (x = ${x}).`, + ); - // MEMORIZATION - const matrix: number[][] = [[1, x]]; - matrix.length = m + 1; + // MEMORIZATION + const matrix: number[][] = [[1, x]]; + matrix.length = m + 1; - for (let i: number = 1; i < matrix.length; ++i) matrix[i] = []; + for (let i: number = 1; i < matrix.length; ++i) matrix[i] = []; - // COMPUTE RETURN VALUE - return _Compute_assoc_legendre(n, m, x, matrix); + // COMPUTE RETURN VALUE + return _Compute_assoc_legendre(n, m, x, matrix); } function _Compute_legendre(n: number, x: number, memory: number[]): number { - if (memory.length > n) return memory[n]; + if (memory.length > n) return memory[n]; - const pn_1: number = _Compute_legendre(n - 1, x, memory); - const pn_2: number = _Compute_legendre(n - 2, x, memory); + const pn_1: number = _Compute_legendre(n - 1, x, memory); + const pn_2: number = _Compute_legendre(n - 2, x, memory); - let ret: number = (2 * n - 1) * x * pn_1 - (n - 1) * pn_2; - ret /= n; + let ret: number = (2 * n - 1) * x * pn_1 - (n - 1) * pn_2; + ret /= n; - memory[n] = ret; - return ret; + memory[n] = ret; + return ret; } function _Compute_assoc_legendre( - n: number, - m: number, - x: number, - matrix: number[][], + n: number, + m: number, + x: number, + matrix: number[][], ): number { - if (n < 0) n = -n - 1; + if (n < 0) n = -n - 1; - if (m === 0) return _Compute_legendre(n, x, matrix[0]); - else if (matrix[m].length > n && matrix[m][n] !== undefined) - return matrix[m][n]; + if (m === 0) return _Compute_legendre(n, x, matrix[0]); + else if (matrix[m].length > n && matrix[m][n] !== undefined) + return matrix[m][n]; - const left: number = - (n - m + 1) * - (n - m + 2) * - _Compute_assoc_legendre(n + 1, m - 1, x, matrix); - const right: number = - (n + m - 1) * - (n + m) * - _Compute_assoc_legendre(n - 1, m - 1, x, matrix); + const left: number = + (n - m + 1) * + (n - m + 2) * + _Compute_assoc_legendre(n + 1, m - 1, x, matrix); + const right: number = + (n + m - 1) * (n + m) * _Compute_assoc_legendre(n - 1, m - 1, x, matrix); - let ret: number = (left - right) / (2 * n + 1); - ret /= Math.sqrt(1 - x * x); + let ret: number = (left - right) / (2 * n + 1); + ret /= Math.sqrt(1 - x * x); - matrix[m][n] = ret; - return ret; + matrix[m][n] = ret; + return ret; } diff --git a/src/numeric/special_math/zeta.ts b/src/numeric/special_math/zeta.ts index 4b732152..89321049 100644 --- a/src/numeric/special_math/zeta.ts +++ b/src/numeric/special_math/zeta.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -13,44 +14,44 @@ import { tgamma } from "./gamma"; * @reference http://en.cppreference.com/w/cpp/numeric/special_math/riemann_zeta */ export function riemann_zeta(arg: number): number { - if (arg < 0) return _Negative(arg); - else if (arg === 0) return -0.5; - else if (arg < 1) return _Fractional(arg); - else if (arg === 1) return Infinity; - else return _Positive(arg); + if (arg < 0) return _Negative(arg); + else if (arg === 0) return -0.5; + else if (arg < 1) return _Fractional(arg); + else if (arg === 1) return Infinity; + else return _Positive(arg); } function _Negative(arg: number): number { - return ( - Math.pow(2, arg) * - Math.pow(Math.PI, arg - 1) * - Math.sin((Math.PI * arg) / 2) * - tgamma(1 - arg) * - riemann_zeta(1 - arg) - ); + return ( + Math.pow(2, arg) * + Math.pow(Math.PI, arg - 1) * + Math.sin((Math.PI * arg) / 2) * + tgamma(1 - arg) * + riemann_zeta(1 - arg) + ); } function _Fractional(arg: number): number { - const divider: number = 1 - Math.pow(2, 1 - arg); - const sigma: number = MathUtil.sigma( - function (n: number): number { - return Math.pow(-1, n - 1) * Math.pow(n, -arg); - }, - 1, - INFINITY, - ); + const divider: number = 1 - Math.pow(2, 1 - arg); + const sigma: number = MathUtil.sigma( + function (n: number): number { + return Math.pow(-1, n - 1) * Math.pow(n, -arg); + }, + 1, + INFINITY, + ); - return sigma / divider; + return sigma / divider; } function _Positive(arg: number): number { - return MathUtil.sigma( - function (n: number): number { - return Math.pow(n, -arg); - }, - 1, - INFINITY, - ); + return MathUtil.sigma( + function (n: number): number { + return Math.pow(n, -arg); + }, + 1, + INFINITY, + ); } const INFINITY = 100 * 1000; diff --git a/src/ranges/algorithm/binary_search.ts b/src/ranges/algorithm/binary_search.ts index 21eeeb9c..553e124f 100644 --- a/src/ranges/algorithm/binary_search.ts +++ b/src/ranges/algorithm/binary_search.ts @@ -1,17 +1,16 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ import * as base from "../../algorithm/binary_search"; - -import { IForwardContainer } from "../container/IForwardContainer"; -import { Pair } from "../../utility/Pair"; -import { begin, end } from "../../iterator/factory"; import { less } from "../../functional/comparators"; - import { Comparator } from "../../internal/functional/Comparator"; +import { begin, end } from "../../iterator/factory"; +import { Pair } from "../../utility/Pair"; +import { IForwardContainer } from "../container/IForwardContainer"; /* ========================================================= BINARY SEARCH @@ -26,11 +25,11 @@ import { Comparator } from "../../internal/functional/Comparator"; * @return Iterator to the first element equal or after the val. */ export function lower_bound | IForwardContainer>( - range: Range, - val: IForwardContainer.ValueType, - comp: Comparator> = less, + range: Range, + val: IForwardContainer.ValueType, + comp: Comparator> = less, ): IForwardContainer.IteratorType { - return base.lower_bound(begin(range), end(range), val, comp); + return base.lower_bound(begin(range), end(range), val, comp); } /** @@ -43,11 +42,11 @@ export function lower_bound | IForwardContainer>( * @return Iterator to the first element after the key. */ export function upper_bound | IForwardContainer>( - range: Range, - val: IForwardContainer.ValueType, - comp: Comparator> = less, + range: Range, + val: IForwardContainer.ValueType, + comp: Comparator> = less, ): IForwardContainer.IteratorType { - return base.upper_bound(begin(range), end(range), val, comp); + return base.upper_bound(begin(range), end(range), val, comp); } /** @@ -60,14 +59,14 @@ export function upper_bound | IForwardContainer>( * @return Pair of {@link lower_bound} and {@link upper_bound}. */ export function equal_range | IForwardContainer>( - range: Range, - val: IForwardContainer.ValueType, - comp: Comparator> = less, + range: Range, + val: IForwardContainer.ValueType, + comp: Comparator> = less, ): Pair< - IForwardContainer.IteratorType, - IForwardContainer.IteratorType + IForwardContainer.IteratorType, + IForwardContainer.IteratorType > { - return base.equal_range(begin(range), end(range), val, comp); + return base.equal_range(begin(range), end(range), val, comp); } /** @@ -80,11 +79,11 @@ export function equal_range | IForwardContainer>( * @return Whether the value exists or not. */ export function binary_search< - Range extends Array | IForwardContainer, + Range extends Array | IForwardContainer, >( - range: Range, - val: IForwardContainer.ValueType, - comp: Comparator> = less, + range: Range, + val: IForwardContainer.ValueType, + comp: Comparator> = less, ): boolean { - return base.binary_search(begin(range), end(range), val, comp); + return base.binary_search(begin(range), end(range), val, comp); } diff --git a/src/ranges/algorithm/heap.ts b/src/ranges/algorithm/heap.ts index 49c4cf37..61ce5130 100644 --- a/src/ranges/algorithm/heap.ts +++ b/src/ranges/algorithm/heap.ts @@ -1,15 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ import * as base from "../../algorithm/heap"; - -import { IRandomAccessContainer } from "../container/IRandomAccessContainer"; +import { less } from "../../functional/comparators"; import { Comparator } from "../../internal/functional/Comparator"; import { begin, end } from "../../iterator/factory"; -import { less } from "../../functional/comparators"; +import { IRandomAccessContainer } from "../container/IRandomAccessContainer"; /* --------------------------------------------------------- PUSH & POP @@ -21,12 +21,12 @@ import { less } from "../../functional/comparators"; * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function make_heap< - Range extends Array | IRandomAccessContainer, + Range extends Array | IRandomAccessContainer, >( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): void { - return base.make_heap(begin(range), end(range), comp); + return base.make_heap(begin(range), end(range), comp); } /** @@ -36,12 +36,12 @@ export function make_heap< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function push_heap< - Range extends Array | IRandomAccessContainer, + Range extends Array | IRandomAccessContainer, >( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): void { - return base.push_heap(begin(range), end(range), comp); + return base.push_heap(begin(range), end(range), comp); } /** @@ -51,12 +51,12 @@ export function push_heap< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function pop_heap< - Range extends Array | IRandomAccessContainer, + Range extends Array | IRandomAccessContainer, >( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): void { - return base.pop_heap(begin(range), end(range), comp); + return base.pop_heap(begin(range), end(range), comp); } /* --------------------------------------------------------- @@ -71,10 +71,10 @@ export function pop_heap< * @return Whether the range is heap. */ export function is_heap | IRandomAccessContainer>( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): boolean { - return base.is_heap(begin(range), end(range), comp); + return base.is_heap(begin(range), end(range), comp); } /** @@ -86,12 +86,12 @@ export function is_heap | IRandomAccessContainer>( * @return Iterator to the first element not in heap order. */ export function is_heap_until< - Range extends Array | IRandomAccessContainer, + Range extends Array | IRandomAccessContainer, >( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): IRandomAccessContainer.IteratorType { - return base.is_heap_until(begin(range), end(range), comp); + return base.is_heap_until(begin(range), end(range), comp); } /** @@ -101,10 +101,10 @@ export function is_heap_until< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function sort_heap< - Range extends Array | IRandomAccessContainer, + Range extends Array | IRandomAccessContainer, >( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): void { - return base.sort_heap(begin(range), end(range), comp); + return base.sort_heap(begin(range), end(range), comp); } diff --git a/src/ranges/algorithm/iterations.ts b/src/ranges/algorithm/iterations.ts index c48ff55b..21d7a6b6 100644 --- a/src/ranges/algorithm/iterations.ts +++ b/src/ranges/algorithm/iterations.ts @@ -1,28 +1,27 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ import * as base from "../../algorithm/iterations"; - -import { IForwardContainer } from "../container/IForwardContainer"; -import { Pair } from "../../utility/Pair"; -import { begin, end } from "../../iterator/factory"; -import { size } from "../../iterator/global"; import { equal_to, less } from "../../functional/comparators"; - -import { UnaryPredicator } from "../../internal/functional/UnaryPredicator"; import { BinaryPredicator } from "../../internal/functional/BinaryPredicator"; import { Comparator } from "../../internal/functional/Comparator"; import { Temporary } from "../../internal/functional/Temporary"; +import { UnaryPredicator } from "../../internal/functional/UnaryPredicator"; +import { begin, end } from "../../iterator/factory"; +import { size } from "../../iterator/global"; +import { Pair } from "../../utility/Pair"; +import { IForwardContainer } from "../container/IForwardContainer"; type BinaryPredicatorInferrer< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, > = BinaryPredicator< - IForwardContainer.ValueType, - IForwardContainer.ValueType + IForwardContainer.ValueType, + IForwardContainer.ValueType >; /* --------------------------------------------------------- @@ -37,10 +36,10 @@ type BinaryPredicatorInferrer< * @return The function *fn* itself. */ export function for_each< - Range extends Array | IForwardContainer, - Func extends (val: IForwardContainer.ValueType) => any, + Range extends Array | IForwardContainer, + Func extends (val: IForwardContainer.ValueType) => any, >(range: Range, fn: Func): Func { - return base.for_each(begin(range), end(range), fn); + return base.for_each(begin(range), end(range), fn); } /** @@ -53,10 +52,10 @@ export function for_each< * @return Iterator advanced from *first* for *n* steps. */ export function for_each_n< - Range extends Array | IForwardContainer, - Func extends (val: IForwardContainer.ValueType) => any, + Range extends Array | IForwardContainer, + Func extends (val: IForwardContainer.ValueType) => any, >(range: Range, n: number, fn: Func): IForwardContainer.IteratorType { - return base.for_each_n(begin(range), n, fn); + return base.for_each_n(begin(range), n, fn); } /* --------------------------------------------------------- @@ -71,10 +70,10 @@ export function for_each_n< * @return Whether the *pred* returns always `true` for all elements. */ export function all_of | IForwardContainer>( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): boolean { - return base.all_of(begin(range), end(range), pred); + return base.all_of(begin(range), end(range), pred); } /** @@ -86,10 +85,10 @@ export function all_of | IForwardContainer>( * @return Whether the *pred* returns at least a `true` for all elements. */ export function any_of | IForwardContainer>( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): boolean { - return base.any_of(begin(range), end(range), pred); + return base.any_of(begin(range), end(range), pred); } /** @@ -101,10 +100,10 @@ export function any_of | IForwardContainer>( * @return Whether the *pred* doesn't return `true` for all elements. */ export function none_of | IForwardContainer>( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): boolean { - return base.none_of(begin(range), end(range), pred); + return base.none_of(begin(range), end(range), pred); } /** @@ -117,8 +116,8 @@ export function none_of | IForwardContainer>( * @return Whether two ranges are equal. */ export function equal< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, >(range1: Range1, range2: Range2): boolean; /** @@ -131,24 +130,24 @@ export function equal< * @return Whether two ranges are equal. */ export function equal< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - pred: BinaryPredicatorInferrer, + range1: Range1, + range2: Range2, + pred: BinaryPredicatorInferrer, ): boolean; export function equal< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - pred: BinaryPredicatorInferrer = equal_to, + range1: Range1, + range2: Range2, + pred: BinaryPredicatorInferrer = equal_to, ): boolean { - if (size(range1) !== size(range2)) return false; - else return base.equal(begin(range1), end(range1), begin(range2), pred); + if (size(range1) !== size(range2)) return false; + else return base.equal(begin(range1), end(range1), begin(range2), pred); } /** @@ -161,20 +160,20 @@ export function equal< * @return Whether the 1st range precedes the 2nd. */ export function lexicographical_compare< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, >( - range1: Range1, - range2: Range2, - comp: BinaryPredicatorInferrer = less, + range1: Range1, + range2: Range2, + comp: BinaryPredicatorInferrer = less, ): boolean { - return base.lexicographical_compare( - begin(range1), - end(range1), - begin(range2), - end(range2), - comp, - ); + return base.lexicographical_compare( + begin(range1), + end(range1), + begin(range2), + end(range2), + comp, + ); } /* --------------------------------------------------------- @@ -189,10 +188,10 @@ export function lexicographical_compare< * @return Iterator to the first element {@link equal to equal_to} the value. */ export function find | IForwardContainer>( - range: Range, - val: IForwardContainer.ValueType, + range: Range, + val: IForwardContainer.ValueType, ): IForwardContainer.IteratorType { - return base.find(begin(range), end(range), val); + return base.find(begin(range), end(range), val); } /** @@ -204,10 +203,10 @@ export function find | IForwardContainer>( * @return Iterator to the first element *pred* returns `true`. */ export function find_if | IForwardContainer>( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): IForwardContainer.IteratorType { - return base.find_if(begin(range), end(range), pred); + return base.find_if(begin(range), end(range), pred); } /** @@ -219,10 +218,10 @@ export function find_if | IForwardContainer>( * @return Iterator to the first element *pred* returns `false`. */ export function find_if_not | IForwardContainer>( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): IForwardContainer.IteratorType { - return base.find_if_not(begin(range), end(range), pred); + return base.find_if_not(begin(range), end(range), pred); } /** @@ -234,8 +233,8 @@ export function find_if_not | IForwardContainer>( * @return Iterator to the first element of the last sub range. */ export function find_end< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, >(range1: Range1, range2: Range2): IForwardContainer.IteratorType; /** @@ -248,29 +247,29 @@ export function find_end< * @return Iterator to the first element of the last sub range. */ export function find_end< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - pred: BinaryPredicatorInferrer, + range1: Range1, + range2: Range2, + pred: BinaryPredicatorInferrer, ): IForwardContainer.IteratorType; export function find_end< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - pred: BinaryPredicatorInferrer = equal_to, + range1: Range1, + range2: Range2, + pred: BinaryPredicatorInferrer = equal_to, ): IForwardContainer.IteratorType { - return base.find_end( - begin(range1), - end(range1), - begin(range2), - end(range2), - pred, - ); + return base.find_end( + begin(range1), + end(range1), + begin(range2), + end(range2), + pred, + ); } /** @@ -282,8 +281,8 @@ export function find_end< * @return Iterator to the first element of the first sub range. */ export function find_first_of< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, >(range1: Range1, range2: Range2): IForwardContainer.IteratorType; /** @@ -296,29 +295,29 @@ export function find_first_of< * @return Iterator to the first element of the first sub range. */ export function find_first_of< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - pred: BinaryPredicatorInferrer, + range1: Range1, + range2: Range2, + pred: BinaryPredicatorInferrer, ): IForwardContainer.IteratorType; export function find_first_of< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - pred: BinaryPredicatorInferrer = equal_to, + range1: Range1, + range2: Range2, + pred: BinaryPredicatorInferrer = equal_to, ): IForwardContainer.IteratorType { - return base.find_first_of( - begin(range1), - end(range1), - begin(range2), - end(range2), - pred, - ); + return base.find_first_of( + begin(range1), + end(range1), + begin(range2), + end(range2), + pred, + ); } /** @@ -330,12 +329,12 @@ export function find_first_of< * @return Iterator to the first element of adjacent find. */ export function adjacent_find< - Range extends Array | IForwardContainer, + Range extends Array | IForwardContainer, >( - range: Range, - pred: Comparator> = equal_to, + range: Range, + pred: Comparator> = equal_to, ): IForwardContainer.IteratorType { - return base.adjacent_find(begin(range), end(range), pred); + return base.adjacent_find(begin(range), end(range), pred); } /** @@ -347,8 +346,8 @@ export function adjacent_find< * @return Iterator to the first element of the sub range. */ export function search< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer.SimilarType, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer.SimilarType, >(range1: Range1, range2: Range2): IForwardContainer.IteratorType; /** @@ -361,29 +360,29 @@ export function search< * @return Iterator to the first element of the sub range. */ export function search< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - pred: BinaryPredicatorInferrer, + range1: Range1, + range2: Range2, + pred: BinaryPredicatorInferrer, ): IForwardContainer.IteratorType; export function search< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - pred: BinaryPredicatorInferrer = equal_to, + range1: Range1, + range2: Range2, + pred: BinaryPredicatorInferrer = equal_to, ): IForwardContainer.IteratorType { - return base.search( - begin(range1), - end(range1), - begin(range2), - end(range2), - pred, - ); + return base.search( + begin(range1), + end(range1), + begin(range2), + end(range2), + pred, + ); } /** @@ -397,12 +396,12 @@ export function search< * @return Iterator to the first element of the repetition. */ export function search_n | IForwardContainer>( - range: Range, - count: number, - val: IForwardContainer.ValueType, - pred: Comparator> = equal_to, + range: Range, + count: number, + val: IForwardContainer.ValueType, + pred: Comparator> = equal_to, ): IForwardContainer.IteratorType { - return base.search_n(begin(range), end(range), count, val, pred); + return base.search_n(begin(range), end(range), count, val, pred); } /** @@ -414,14 +413,14 @@ export function search_n | IForwardContainer>( * @return A {@link Pair} of mismatched positions. */ export function mismatch< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer.SimilarType, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer.SimilarType, >( - range1: Range1, - range2: Range2, + range1: Range1, + range2: Range2, ): Pair< - IForwardContainer.IteratorType, - IForwardContainer.IteratorType + IForwardContainer.IteratorType, + IForwardContainer.IteratorType >; /** @@ -434,42 +433,42 @@ export function mismatch< * @return A {@link Pair} of mismatched positions. */ export function mismatch< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - pred: BinaryPredicatorInferrer, + range1: Range1, + range2: Range2, + pred: BinaryPredicatorInferrer, ): Pair< - IForwardContainer.IteratorType, - IForwardContainer.IteratorType + IForwardContainer.IteratorType, + IForwardContainer.IteratorType >; export function mismatch< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - pred: BinaryPredicatorInferrer = equal_to, + range1: Range1, + range2: Range2, + pred: BinaryPredicatorInferrer = equal_to, ): Pair< - IForwardContainer.IteratorType, - IForwardContainer.IteratorType + IForwardContainer.IteratorType, + IForwardContainer.IteratorType > { - if (size(range1) === size(range2)) - return base.mismatch(begin(range1), end(range1), begin(range2), pred); + if (size(range1) === size(range2)) + return base.mismatch(begin(range1), end(range1), begin(range2), pred); - const limit: number = Math.min(size(range1), size(range2)); - let x: IForwardContainer.IteratorType = begin(range1); - let y: IForwardContainer.IteratorType = begin(range2); + const limit: number = Math.min(size(range1), size(range2)); + let x: IForwardContainer.IteratorType = begin(range1); + let y: IForwardContainer.IteratorType = begin(range2); - for (let i: number = 0; i < limit; ++i) { - if (pred(x.value, y.value) === false) break; + for (let i: number = 0; i < limit; ++i) { + if (pred(x.value, y.value) === false) break; - x = x.next(); - y = y.next(); - } - return new Pair(x, y); + x = x.next(); + y = y.next(); + } + return new Pair(x, y); } /* --------------------------------------------------------- @@ -484,10 +483,10 @@ export function mismatch< * @return The matched count. */ export function count | IForwardContainer>( - range: Range, - val: IForwardContainer.ValueType, + range: Range, + val: IForwardContainer.ValueType, ): number { - return base.count(begin(range), end(range), val); + return base.count(begin(range), end(range), val); } /** @@ -499,8 +498,8 @@ export function count | IForwardContainer>( * @return The matched count. */ export function count_if | IForwardContainer>( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): number { - return base.count_if(begin(range), end(range), pred); + return base.count_if(begin(range), end(range), pred); } diff --git a/src/ranges/algorithm/mathematics.ts b/src/ranges/algorithm/mathematics.ts index 3239b531..522d524a 100644 --- a/src/ranges/algorithm/mathematics.ts +++ b/src/ranges/algorithm/mathematics.ts @@ -1,20 +1,19 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ import * as base from "../../algorithm/mathematics"; - -import { IBidirectionalContainer } from "../container/IBidirectionalContainer"; -import { IForwardContainer } from "../container/IForwardContainer"; -import { Pair } from "../../utility/Pair"; -import { less, equal_to } from "../../functional/comparators"; -import { begin, end } from "../../iterator/factory"; -import { size } from "../../iterator/global"; - +import { equal_to, less } from "../../functional/comparators"; import { Comparator } from "../../internal/functional/Comparator"; import { Temporary } from "../../internal/functional/Temporary"; +import { begin, end } from "../../iterator/factory"; +import { size } from "../../iterator/global"; +import { Pair } from "../../utility/Pair"; +import { IBidirectionalContainer } from "../container/IBidirectionalContainer"; +import { IForwardContainer } from "../container/IForwardContainer"; /* --------------------------------------------------------- MIN & MAX @@ -28,10 +27,10 @@ import { Temporary } from "../../internal/functional/Temporary"; * @return Iterator to the minimum element. */ export function min_element | IForwardContainer>( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): IForwardContainer.IteratorType { - return base.min_element(begin(range), end(range), comp); + return base.min_element(begin(range), end(range), comp); } /** @@ -43,10 +42,10 @@ export function min_element | IForwardContainer>( * @return Iterator to the maximum element. */ export function max_element | IForwardContainer>( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): IForwardContainer.IteratorType { - return base.max_element(begin(range), end(range), comp); + return base.max_element(begin(range), end(range), comp); } /** @@ -58,15 +57,15 @@ export function max_element | IForwardContainer>( * @return A {@link Pair} of iterators to the minimum & maximum elements. */ export function minmax_element< - Range extends Array | IForwardContainer, + Range extends Array | IForwardContainer, >( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): Pair< - IForwardContainer.IteratorType, - IForwardContainer.IteratorType + IForwardContainer.IteratorType, + IForwardContainer.IteratorType > { - return base.minmax_element(begin(range), end(range), comp); + return base.minmax_element(begin(range), end(range), comp); } /* --------------------------------------------------------- @@ -82,21 +81,21 @@ export function minmax_element< * @return Whether permutation or not. */ export function is_permutation< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, >( - range1: Range1, - range2: Range2, - pred: Comparator> = equal_to, + range1: Range1, + range2: Range2, + pred: Comparator> = equal_to, ): boolean { - if (size(range1) !== size(range2)) return false; - else - return base.is_permutation( - begin(range1), - end(range1), - begin(range2), - pred, - ); + if (size(range1) !== size(range2)) return false; + else + return base.is_permutation( + begin(range1), + end(range1), + begin(range2), + pred, + ); } /** @@ -108,12 +107,12 @@ export function is_permutation< * @return Whether the transformation was meaningful. */ export function prev_permutation< - Range extends Array | IBidirectionalContainer, + Range extends Array | IBidirectionalContainer, >( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): boolean { - return base.prev_permutation(begin(range), end(range), comp); + return base.prev_permutation(begin(range), end(range), comp); } /** @@ -125,10 +124,10 @@ export function prev_permutation< * @return Whether the transformation was meaningful. */ export function next_permutation< - Range extends Array | IBidirectionalContainer, + Range extends Array | IBidirectionalContainer, >( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): boolean { - return base.next_permutation(begin(range), end(range), comp); + return base.next_permutation(begin(range), end(range), comp); } diff --git a/src/ranges/algorithm/merge.ts b/src/ranges/algorithm/merge.ts index a5386a0d..11b187f0 100644 --- a/src/ranges/algorithm/merge.ts +++ b/src/ranges/algorithm/merge.ts @@ -1,22 +1,20 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ import * as base from "../../algorithm/merge"; - -import { IBidirectionalContainer } from "../container/IBidirectionalContainer"; -import { IForwardContainer } from "../container/IForwardContainer"; -import { IForwardIterator } from "../../iterator/IForwardIterator"; - -import { Writeonly } from "../../internal/functional/Writeonly"; -import { begin, end } from "../../iterator/factory"; -import { size } from "../../iterator/global"; import { less } from "../../functional/comparators"; - import { Comparator } from "../../internal/functional/Comparator"; import { Temporary } from "../../internal/functional/Temporary"; +import { Writeonly } from "../../internal/functional/Writeonly"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; +import { begin, end } from "../../iterator/factory"; +import { size } from "../../iterator/global"; +import { IBidirectionalContainer } from "../container/IBidirectionalContainer"; +import { IForwardContainer } from "../container/IForwardContainer"; /* --------------------------------------------------------- MERGE @@ -32,25 +30,25 @@ import { Temporary } from "../../internal/functional/Temporary"; * @return Output Iterator of the last position by advancing. */ export function merge< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range1: Range1, - range2: Range2, - output: OutputIterator, - comp: Comparator> = less, + range1: Range1, + range2: Range2, + output: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - return base.merge( - begin(range1), - end(range1), - begin(range2), - end(range2), - output, - comp, - ); + return base.merge( + begin(range1), + end(range1), + begin(range2), + end(range2), + output, + comp, + ); } /** @@ -61,13 +59,13 @@ export function merge< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function inplace_merge< - Range extends Array | IBidirectionalContainer, + Range extends Array | IBidirectionalContainer, >( - range: Range, - middle: IBidirectionalContainer.IteratorType, - comp: Comparator> = less, + range: Range, + middle: IBidirectionalContainer.IteratorType, + comp: Comparator> = less, ): void { - return base.inplace_merge(begin(range), middle, end(range), comp); + return base.inplace_merge(begin(range), middle, end(range), comp); } /* --------------------------------------------------------- @@ -83,22 +81,22 @@ export function inplace_merge< * @return Whether [first, last1) includes [first2, last2). */ export function includes< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, >( - range1: Range1, - range2: Range2, - comp: Comparator> = less, + range1: Range1, + range2: Range2, + comp: Comparator> = less, ): boolean { - if (size(range1) < size(range2)) return false; - else - return base.includes( - begin(range1), - end(range1), - begin(range2), - end(range2), - comp, - ); + if (size(range1) < size(range2)) return false; + else + return base.includes( + begin(range1), + end(range1), + begin(range2), + end(range2), + comp, + ); } /** @@ -112,25 +110,25 @@ export function includes< * @return Output Iterator of the last position by advancing. */ export function set_union< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range1: Range1, - range2: Range2, - output: OutputIterator, - comp: Comparator> = less, + range1: Range1, + range2: Range2, + output: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - return base.set_union( - begin(range1), - end(range1), - begin(range2), - end(range2), - output, - comp, - ); + return base.set_union( + begin(range1), + end(range1), + begin(range2), + end(range2), + output, + comp, + ); } /** @@ -144,25 +142,25 @@ export function set_union< * @return Output Iterator of the last position by advancing. */ export function set_intersection< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range1: Range1, - range2: Range2, - output: OutputIterator, - comp: Comparator> = less, + range1: Range1, + range2: Range2, + output: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - return base.set_intersection( - begin(range1), - end(range1), - begin(range2), - end(range2), - output, - comp, - ); + return base.set_intersection( + begin(range1), + end(range1), + begin(range2), + end(range2), + output, + comp, + ); } /** @@ -176,25 +174,25 @@ export function set_intersection< * @return Output Iterator of the last position by advancing. */ export function set_difference< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range1: Range1, - range2: Range2, - output: OutputIterator, - comp: Comparator> = less, + range1: Range1, + range2: Range2, + output: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - return base.set_difference( - begin(range1), - end(range1), - begin(range2), - end(range2), - output, - comp, - ); + return base.set_difference( + begin(range1), + end(range1), + begin(range2), + end(range2), + output, + comp, + ); } /** @@ -208,23 +206,23 @@ export function set_difference< * @return Output Iterator of the last position by advancing. */ export function set_symmetric_difference< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range1: Range1, - range2: Range2, - output: OutputIterator, - comp: Comparator> = less, + range1: Range1, + range2: Range2, + output: OutputIterator, + comp: Comparator> = less, ): OutputIterator { - return base.set_symmetric_difference( - begin(range1), - end(range1), - begin(range2), - end(range2), - output, - comp, - ); + return base.set_symmetric_difference( + begin(range1), + end(range1), + begin(range2), + end(range2), + output, + comp, + ); } diff --git a/src/ranges/algorithm/modifiers.ts b/src/ranges/algorithm/modifiers.ts index 7b6d0d55..03e8d7fd 100644 --- a/src/ranges/algorithm/modifiers.ts +++ b/src/ranges/algorithm/modifiers.ts @@ -1,44 +1,42 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ import * as base from "../../algorithm/modifiers"; - -import { IBidirectionalContainer } from "../container/IBidirectionalContainer"; -import { IForwardContainer } from "../container/IForwardContainer"; -import { IRandomAccessContainer } from "../container/IRandomAccessContainer"; - -import { IBidirectionalIterator } from "../../iterator/IBidirectionalIterator"; -import { IForwardIterator } from "../../iterator/IForwardIterator"; import { IPointer } from "../../functional/IPointer"; - +import { equal_to } from "../../functional/comparators"; import { BinaryPredicator } from "../../internal/functional/BinaryPredicator"; +import { Temporary } from "../../internal/functional/Temporary"; import { UnaryPredicator } from "../../internal/functional/UnaryPredicator"; import { Writeonly } from "../../internal/functional/Writeonly"; -import { Temporary } from "../../internal/functional/Temporary"; +import { IBidirectionalIterator } from "../../iterator/IBidirectionalIterator"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; import { begin, end } from "../../iterator/factory"; -import { equal_to } from "../../functional/comparators"; +import { IBidirectionalContainer } from "../container/IBidirectionalContainer"; +import { IForwardContainer } from "../container/IForwardContainer"; +import { IRandomAccessContainer } from "../container/IRandomAccessContainer"; type UnaryOperatorInferrer< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, > = ( - val: IForwardContainer.ValueType, + val: IForwardContainer.ValueType, ) => IPointer.ValueType; type BinaryOperatorInferrer< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, > = ( - x: IForwardContainer.ValueType, - y: IForwardContainer.ValueType, + x: IForwardContainer.ValueType, + y: IForwardContainer.ValueType, ) => IPointer.ValueType; /* --------------------------------------------------------- @@ -53,12 +51,12 @@ type BinaryOperatorInferrer< * @return Output Iterator of the last position by advancing. */ export function copy< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >(range: Range, output: OutputIterator): OutputIterator { - return base.copy(begin(range), end(range), output); + return base.copy(begin(range), end(range), output); } /** @@ -71,12 +69,12 @@ export function copy< * @return Output Iterator of the last position by advancing. */ export function copy_n< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >(range: Range, n: number, output: OutputIterator): OutputIterator { - return base.copy_n(begin(range), n, output); + return base.copy_n(begin(range), n, output); } /** @@ -89,16 +87,16 @@ export function copy_n< * @return Output Iterator of the last position by advancing. */ export function copy_if< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - output: OutputIterator, - pred: UnaryPredicator>, + range: Range, + output: OutputIterator, + pred: UnaryPredicator>, ): OutputIterator { - return base.copy_if(begin(range), end(range), output, pred); + return base.copy_if(begin(range), end(range), output, pred); } /** @@ -110,15 +108,15 @@ export function copy_if< * @return Output Iterator of the last position by advancing. */ export function copy_backward< - Range extends Array | IBidirectionalContainer, - OutputIterator extends Writeonly< - IBidirectionalIterator< - IBidirectionalContainer.ValueType, - OutputIterator - > - >, + Range extends Array | IBidirectionalContainer, + OutputIterator extends Writeonly< + IBidirectionalIterator< + IBidirectionalContainer.ValueType, + OutputIterator + > + >, >(range: Range, output: OutputIterator): OutputIterator { - return base.copy_backward(begin(range), end(range), output); + return base.copy_backward(begin(range), end(range), output); } /** @@ -130,10 +128,10 @@ export function copy_backward< * @return Output Iterator of the last position by advancing. */ export function fill | IForwardContainer>( - range: Range, - value: IForwardContainer.ValueType, + range: Range, + value: IForwardContainer.ValueType, ): void { - return base.fill(begin(range), end(range), value); + return base.fill(begin(range), end(range), value); } /** @@ -146,11 +144,11 @@ export function fill | IForwardContainer>( * @return Output Iterator of the last position by advancing. */ export function fill_n | IForwardContainer>( - range: Range, - n: number, - value: IForwardContainer.ValueType, + range: Range, + n: number, + value: IForwardContainer.ValueType, ): IForwardContainer.IteratorType { - return base.fill_n(begin(range), n, value); + return base.fill_n(begin(range), n, value); } /** @@ -163,14 +161,14 @@ export function fill_n | IForwardContainer>( * @return Output Iterator of the last position by advancing. */ export function transform< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - result: OutputIterator, - op: UnaryOperatorInferrer, + range: Range, + result: OutputIterator, + op: UnaryOperatorInferrer, ): OutputIterator; /** @@ -184,30 +182,30 @@ export function transform< * @return Output Iterator of the last position by advancing. */ export function transform< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range1, - first: Range2, - result: OutputIterator, - op: BinaryOperatorInferrer, + range: Range1, + first: Range2, + result: OutputIterator, + op: BinaryOperatorInferrer, ): OutputIterator; export function transform | IForwardContainer>( - range1: Range1, - ...args: any[] + range1: Range1, + ...args: any[] ): any { - const fn: Function = base.transform.bind( - undefined, - begin(range1), - end(range1), - ); - if (args.length === 3) return fn(...args); - // args: #4 - else return fn(end(args[1]), args[2], args[3]); + const fn: Function = base.transform.bind( + undefined, + begin(range1), + end(range1), + ); + if (args.length === 3) return fn(...args); + // args: #4 + else return fn(end(args[1]), args[2], args[3]); } /** @@ -217,10 +215,10 @@ export function transform | IForwardContainer>( * @param gen The generator function. */ export function generate | IForwardContainer>( - range: Range, - gen: () => IForwardContainer.ValueType, + range: Range, + gen: () => IForwardContainer.ValueType, ): void { - return base.generate(begin(range), end(range), gen); + return base.generate(begin(range), end(range), gen); } /** @@ -233,11 +231,11 @@ export function generate | IForwardContainer>( * @return Forward Iterator to the last position by advancing. */ export function generate_n | IForwardContainer>( - range: Range, - n: number, - gen: () => IForwardContainer.ValueType, + range: Range, + n: number, + gen: () => IForwardContainer.ValueType, ): IForwardContainer.IteratorType { - return base.generate_n(begin(range), n, gen); + return base.generate_n(begin(range), n, gen); } /* --------------------------------------------------------- @@ -252,10 +250,10 @@ export function generate_n | IForwardContainer>( * @returns Whether unique or not. */ export function is_unique | IForwardContainer>( - range: Range, - pred: BinaryPredicator> = equal_to, + range: Range, + pred: BinaryPredicator> = equal_to, ): boolean { - return base.is_unique(begin(range), end(range), pred); + return base.is_unique(begin(range), end(range), pred); } /** @@ -267,10 +265,10 @@ export function is_unique | IForwardContainer>( * @return Input iterator to the last element not removed. */ export function unique | IForwardContainer>( - range: Range, - pred: BinaryPredicator> = equal_to, + range: Range, + pred: BinaryPredicator> = equal_to, ): IForwardContainer.IteratorType { - return base.unique(begin(range), end(range), pred); + return base.unique(begin(range), end(range), pred); } /** @@ -283,16 +281,16 @@ export function unique | IForwardContainer>( * @return Output Iterator of the last position by advancing. */ export function unique_copy< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - output: OutputIterator, - pred: BinaryPredicator> = equal_to, + range: Range, + output: OutputIterator, + pred: BinaryPredicator> = equal_to, ): OutputIterator { - return base.unique_copy(begin(range), end(range), output, pred); + return base.unique_copy(begin(range), end(range), output, pred); } /** @@ -304,10 +302,10 @@ export function unique_copy< * @return Iterator tho the last element not removed. */ export function remove | IForwardContainer>( - range: Range, - val: IForwardContainer.ValueType, + range: Range, + val: IForwardContainer.ValueType, ): IForwardContainer.IteratorType { - return base.remove(begin(range), end(range), val); + return base.remove(begin(range), end(range), val); } /** @@ -319,10 +317,10 @@ export function remove | IForwardContainer>( * @return Iterator tho the last element not removed. */ export function remove_if | IForwardContainer>( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): IForwardContainer.IteratorType { - return base.remove_if(begin(range), end(range), pred); + return base.remove_if(begin(range), end(range), pred); } /** @@ -335,16 +333,16 @@ export function remove_if | IForwardContainer>( * @return Output Iterator of the last position by advancing. */ export function remove_copy< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - output: OutputIterator, - val: IForwardContainer.ValueType, + range: Range, + output: OutputIterator, + val: IForwardContainer.ValueType, ): OutputIterator { - return base.remove_copy(begin(range), end(range), output, val); + return base.remove_copy(begin(range), end(range), output, val); } /** @@ -357,16 +355,16 @@ export function remove_copy< * @return Output Iterator of the last position by advancing. */ export function remove_copy_if< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - output: OutputIterator, - pred: UnaryPredicator>, + range: Range, + output: OutputIterator, + pred: UnaryPredicator>, ): OutputIterator { - return base.remove_copy_if(begin(range), end(range), output, pred); + return base.remove_copy_if(begin(range), end(range), output, pred); } /* --------------------------------------------------------- @@ -380,11 +378,11 @@ export function remove_copy_if< * @param new_val Specific value to be changed. */ export function replace | IForwardContainer>( - range: Range, - old_val: IForwardContainer.ValueType, - new_val: IForwardContainer.ValueType, + range: Range, + old_val: IForwardContainer.ValueType, + new_val: IForwardContainer.ValueType, ): void { - return base.replace(begin(range), end(range), old_val, new_val); + return base.replace(begin(range), end(range), old_val, new_val); } /** @@ -395,11 +393,11 @@ export function replace | IForwardContainer>( * @param new_val Specific value to be changed. */ export function replace_if | IForwardContainer>( - range: Range, - pred: UnaryPredicator>, - new_val: IForwardContainer.ValueType, + range: Range, + pred: UnaryPredicator>, + new_val: IForwardContainer.ValueType, ): void { - return base.replace_if(begin(range), end(range), pred, new_val); + return base.replace_if(begin(range), end(range), pred, new_val); } /** @@ -413,23 +411,17 @@ export function replace_if | IForwardContainer>( * @return Output Iterator of the last position by advancing. */ export function replace_copy< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - output: OutputIterator, - old_val: IForwardContainer.ValueType, - new_val: IForwardContainer.ValueType, + range: Range, + output: OutputIterator, + old_val: IForwardContainer.ValueType, + new_val: IForwardContainer.ValueType, ): OutputIterator { - return base.replace_copy( - begin(range), - end(range), - output, - old_val, - new_val, - ); + return base.replace_copy(begin(range), end(range), output, old_val, new_val); } /** @@ -443,23 +435,17 @@ export function replace_copy< * @return Output Iterator of the last position by advancing. */ export function replace_copy_if< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - output: OutputIterator, - pred: UnaryPredicator>, - new_val: IForwardContainer.ValueType, + range: Range, + output: OutputIterator, + pred: UnaryPredicator>, + new_val: IForwardContainer.ValueType, ): OutputIterator { - return base.replace_copy_if( - begin(range), - end(range), - output, - pred, - new_val, - ); + return base.replace_copy_if(begin(range), end(range), output, pred, new_val); } /** @@ -471,14 +457,10 @@ export function replace_copy_if< * @return Forward Iterator of the last position of the 2nd range by advancing. */ export function swap_ranges< - Range1 extends Array | IForwardContainer, - Range2 extends IForwardContainer.SimilarType, + Range1 extends Array | IForwardContainer, + Range2 extends IForwardContainer.SimilarType, >(range1: Range1, range2: Range2): IForwardContainer.IteratorType { - return base.swap_ranges( - begin(range1), - end(range1), - begin(range2), - ); + return base.swap_ranges(begin(range1), end(range1), begin(range2)); } /* --------------------------------------------------------- @@ -490,9 +472,9 @@ export function swap_ranges< * @param range An iterable ranged container. */ export function reverse< - Range extends Array | IBidirectionalContainer, + Range extends Array | IBidirectionalContainer, >(range: Range): void { - return base.reverse(begin(range), end(range)); + return base.reverse(begin(range), end(range)); } /** @@ -504,25 +486,25 @@ export function reverse< * @return Output Iterator of the last position by advancing. */ export function reverse_copy< - Range extends Array | IBidirectionalContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IBidirectionalContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >(range: Range, output: OutputIterator): OutputIterator { - return base.reverse_copy(begin(range), end(range), output); + return base.reverse_copy(begin(range), end(range), output); } export function shift_left | IForwardContainer>( - range: Range, - n: number, + range: Range, + n: number, ): void { - return base.shift_left(begin(range), end(range), n); + return base.shift_left(begin(range), end(range), n); } export function shift_right< - Range extends Array | IBidirectionalContainer, + Range extends Array | IBidirectionalContainer, >(range: Range, n: number): void { - return base.shift_right(begin(range), end(range), n); + return base.shift_right(begin(range), end(range), n); } /** @@ -534,10 +516,10 @@ export function shift_right< * @return Input iterator of the final position in the left side; *middle*. */ export function rotate | IForwardContainer>( - range: Range, - middle: IForwardContainer.IteratorType, + range: Range, + middle: IForwardContainer.IteratorType, ): IForwardContainer.IteratorType { - return base.rotate(begin(range), middle, end(range)); + return base.rotate(begin(range), middle, end(range)); } /** @@ -550,16 +532,16 @@ export function rotate | IForwardContainer>( * @return Output Iterator of the last position by advancing. */ export function rotate_copy< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - middle: IForwardContainer.IteratorType, - output: OutputIterator, + range: Range, + middle: IForwardContainer.IteratorType, + output: OutputIterator, ): OutputIterator { - return base.rotate_copy(begin(range), middle, end(range), output); + return base.rotate_copy(begin(range), middle, end(range), output); } /** @@ -568,7 +550,7 @@ export function rotate_copy< * @param range An iterable ranged container. */ export function shuffle | IRandomAccessContainer>( - range: Range, + range: Range, ): void { - return base.shuffle(begin(range), end(range)); + return base.shuffle(begin(range), end(range)); } diff --git a/src/ranges/algorithm/partition.ts b/src/ranges/algorithm/partition.ts index 57918fc1..4d0cc265 100644 --- a/src/ranges/algorithm/partition.ts +++ b/src/ranges/algorithm/partition.ts @@ -1,19 +1,18 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ import * as base from "../../algorithm/partition"; - -import { IBidirectionalContainer } from "../container/IBidirectionalContainer"; -import { IForwardContainer } from "../container/IForwardContainer"; -import { IForwardIterator } from "../../iterator/IForwardIterator"; -import { Pair } from "../../utility/Pair"; - import { UnaryPredicator } from "../../internal/functional/UnaryPredicator"; import { Writeonly } from "../../internal/functional/Writeonly"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; import { begin, end } from "../../iterator/factory"; +import { Pair } from "../../utility/Pair"; +import { IBidirectionalContainer } from "../container/IBidirectionalContainer"; +import { IForwardContainer } from "../container/IForwardContainer"; /** * Test whether a range is partitioned. @@ -24,12 +23,12 @@ import { begin, end } from "../../iterator/factory"; * @return Whether the range is partition or not. */ export function is_partitioned< - Range extends Array | IForwardContainer, + Range extends Array | IForwardContainer, >( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): boolean { - return base.is_partitioned(begin(range), end(range), pred); + return base.is_partitioned(begin(range), end(range), pred); } /** @@ -41,12 +40,12 @@ export function is_partitioned< * @return Iterator to the first element of the second section. */ export function partition_point< - Range extends Array | IForwardContainer, + Range extends Array | IForwardContainer, >( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): IForwardContainer.IteratorType { - return base.partition_point(begin(range), end(range), pred); + return base.partition_point(begin(range), end(range), pred); } /** @@ -58,12 +57,12 @@ export function partition_point< * @return Iterator to the first element of the second section. */ export function partition< - Range extends Array | IBidirectionalContainer, + Range extends Array | IBidirectionalContainer, >( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): IBidirectionalContainer.IteratorType { - return base.partition(begin(range), end(range), pred); + return base.partition(begin(range), end(range), pred); } /** @@ -75,12 +74,12 @@ export function partition< * @return Iterator to the first element of the second section. */ export function stable_partition< - Range extends Array | IBidirectionalContainer, + Range extends Array | IBidirectionalContainer, >( - range: Range, - pred: UnaryPredicator>, + range: Range, + pred: UnaryPredicator>, ): IBidirectionalContainer.IteratorType { - return base.stable_partition(begin(range), end(range), pred); + return base.stable_partition(begin(range), end(range), pred); } /** @@ -94,24 +93,24 @@ export function stable_partition< * @return Iterator to the first element of the second section. */ export function partition_copy< - Range extends Array | IForwardContainer, - OutputIterator1 extends Writeonly< - IForwardIterator, OutputIterator1> - >, - OutputIterator2 extends Writeonly< - IForwardIterator, OutputIterator2> - >, + Range extends Array | IForwardContainer, + OutputIterator1 extends Writeonly< + IForwardIterator, OutputIterator1> + >, + OutputIterator2 extends Writeonly< + IForwardIterator, OutputIterator2> + >, >( - range: Range, - output_true: OutputIterator1, - output_false: OutputIterator2, - pred: UnaryPredicator>, + range: Range, + output_true: OutputIterator1, + output_false: OutputIterator2, + pred: UnaryPredicator>, ): Pair { - return base.partition_copy( - begin(range), - end(range), - output_true, - output_false, - pred, - ); + return base.partition_copy( + begin(range), + end(range), + output_true, + output_false, + pred, + ); } diff --git a/src/ranges/algorithm/random.ts b/src/ranges/algorithm/random.ts index a0070835..c905c705 100644 --- a/src/ranges/algorithm/random.ts +++ b/src/ranges/algorithm/random.ts @@ -1,17 +1,16 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ import * as base from "../../algorithm/random"; - -import { IForwardContainer } from "../container/IForwardContainer"; -import { IForwardIterator } from "../../iterator/IForwardIterator"; import { IPointer } from "../../functional/IPointer"; - import { Writeonly } from "../../internal/functional/Writeonly"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; import { begin, end } from "../../iterator/factory"; +import { IForwardContainer } from "../container/IForwardContainer"; /** * Pick sample elements up. @@ -23,10 +22,10 @@ import { begin, end } from "../../iterator/factory"; * @return Output Iterator of the last position by advancing. */ export function sample< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >(range: Range, first: OutputIterator, n: number): OutputIterator { - return base.sample(begin(range), end(range), first, n); + return base.sample(begin(range), end(range), first, n); } diff --git a/src/ranges/algorithm/sorting.ts b/src/ranges/algorithm/sorting.ts index abaaa8d0..61474f71 100644 --- a/src/ranges/algorithm/sorting.ts +++ b/src/ranges/algorithm/sorting.ts @@ -1,17 +1,16 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ import * as base from "../../algorithm/sorting"; - -import { IForwardContainer } from "../container/IForwardContainer"; -import { IRandomAccessContainer } from "../container/IRandomAccessContainer"; - +import { less } from "../../functional/comparators"; import { Comparator } from "../../internal/functional/Comparator"; import { begin, end } from "../../iterator/factory"; -import { less } from "../../functional/comparators"; +import { IForwardContainer } from "../container/IForwardContainer"; +import { IRandomAccessContainer } from "../container/IRandomAccessContainer"; /* --------------------------------------------------------- SORT @@ -23,10 +22,10 @@ import { less } from "../../functional/comparators"; * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function sort | IRandomAccessContainer>( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): void { - return base.sort(begin(range), end(range), comp); + return base.sort(begin(range), end(range), comp); } /** @@ -36,12 +35,12 @@ export function sort | IRandomAccessContainer>( * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function stable_sort< - Range extends Array | IRandomAccessContainer, + Range extends Array | IRandomAccessContainer, >( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): void { - return base.stable_sort(begin(range), end(range), comp); + return base.stable_sort(begin(range), end(range), comp); } /** @@ -52,13 +51,13 @@ export function stable_sort< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function partial_sort< - Range extends Array | IRandomAccessContainer, + Range extends Array | IRandomAccessContainer, >( - range: Range, - middle: IRandomAccessContainer.IteratorType, - comp: Comparator> = less, + range: Range, + middle: IRandomAccessContainer.IteratorType, + comp: Comparator> = less, ): void { - return base.partial_sort(begin(range), middle, end(range), comp); + return base.partial_sort(begin(range), middle, end(range), comp); } /** @@ -70,20 +69,20 @@ export function partial_sort< * @return Output Iterator of the last position by advancing. */ export function partial_sort_copy< - Range extends Array | IForwardContainer, - Output extends Array | IForwardContainer, + Range extends Array | IForwardContainer, + Output extends Array | IForwardContainer, >( - range: Range, - output: Output, - comp: Comparator> = less, + range: Range, + output: Output, + comp: Comparator> = less, ): IForwardContainer.IteratorType { - return base.partial_sort_copy( - begin(range), - end(range), - begin(output), - end(output), - comp, - ); + return base.partial_sort_copy( + begin(range), + end(range), + begin(output), + end(output), + comp, + ); } /** @@ -95,13 +94,13 @@ export function partial_sort_copy< * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function nth_element< - Range extends Array | IRandomAccessContainer, + Range extends Array | IRandomAccessContainer, >( - range: Range, - nth: IRandomAccessContainer.IteratorType, - comp: Comparator> = less, + range: Range, + nth: IRandomAccessContainer.IteratorType, + comp: Comparator> = less, ): void { - return base.nth_element(begin(range), nth, end(range), comp); + return base.nth_element(begin(range), nth, end(range), comp); } /* --------------------------------------------------------- @@ -116,10 +115,10 @@ export function nth_element< * @return Whether sorted or not. */ export function is_sorted | IForwardContainer>( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): boolean { - return base.is_sorted(begin(range), end(range), comp); + return base.is_sorted(begin(range), end(range), comp); } /** @@ -131,10 +130,10 @@ export function is_sorted | IForwardContainer>( * @return Iterator to the first element who violates the order. */ export function is_sorted_until< - Range extends Array | IForwardContainer, + Range extends Array | IForwardContainer, >( - range: Range, - comp: Comparator> = less, + range: Range, + comp: Comparator> = less, ): IForwardContainer.IteratorType { - return base.is_sorted_until(begin(range), end(range), comp); + return base.is_sorted_until(begin(range), end(range), comp); } diff --git a/src/ranges/container/IBidirectionalContainer.ts b/src/ranges/container/IBidirectionalContainer.ts index 61d39b5d..ce06352f 100644 --- a/src/ranges/container/IBidirectionalContainer.ts +++ b/src/ranges/container/IBidirectionalContainer.ts @@ -1,15 +1,15 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ -import { IForwardContainer } from "./IForwardContainer"; -import { IReverseIterator } from "../../iterator/IReverseIterator"; -import { IReversableIterator } from "../../iterator/IReversableIterator"; -import { IPointer } from "../../functional/IPointer"; - import { Vector } from "../../container/Vector"; +import { IPointer } from "../../functional/IPointer"; +import { IReversableIterator } from "../../iterator/IReversableIterator"; +import { IReverseIterator } from "../../iterator/IReverseIterator"; +import { IForwardContainer } from "./IForwardContainer"; /** * Bidirection iterable container. @@ -18,59 +18,59 @@ import { Vector } from "../../container/Vector"; * @author Jeongho Nam - https://github.com/samchon */ export interface IBidirectionalContainer< - IteratorT extends IReversableIterator< - IPointer.ValueType, - IteratorT, - ReverseIteratorT - >, - ReverseIteratorT extends IReverseIterator< - IPointer.ValueType, - IteratorT, - ReverseIteratorT - >, + IteratorT extends IReversableIterator< + IPointer.ValueType, + IteratorT, + ReverseIteratorT + >, + ReverseIteratorT extends IReverseIterator< + IPointer.ValueType, + IteratorT, + ReverseIteratorT + >, > extends IForwardContainer { - /** - * Reverse iterator to the first element in reverse. - * - * @return Reverse iterator to the first. - */ - rbegin(): ReverseIteratorT; + /** + * Reverse iterator to the first element in reverse. + * + * @return Reverse iterator to the first. + */ + rbegin(): ReverseIteratorT; - /** - * Reverse iterator to the reverse end. - * - * @return Reverse iterator to the end. - */ - rend(): ReverseIteratorT; + /** + * Reverse iterator to the reverse end. + * + * @return Reverse iterator to the end. + */ + rend(): ReverseIteratorT; } export namespace IBidirectionalContainer { - /** - * Deduct iterator type. - */ - export type IteratorType< - Container extends Array | IBidirectionalContainer, - > = Container extends Array - ? Vector.Iterator - : Container extends IBidirectionalContainer - ? Iterator - : unknown; + /** + * Deduct iterator type. + */ + export type IteratorType< + Container extends Array | IBidirectionalContainer, + > = Container extends Array + ? Vector.Iterator + : Container extends IBidirectionalContainer + ? Iterator + : unknown; - /** - * Deduct reverse iterator type. - */ - export type ReverseIteratorType< - Container extends Array | IBidirectionalContainer, - > = Container extends Array - ? Vector.ReverseIterator - : Container extends IBidirectionalContainer - ? ReverseIterator - : unknown; + /** + * Deduct reverse iterator type. + */ + export type ReverseIteratorType< + Container extends Array | IBidirectionalContainer, + > = Container extends Array + ? Vector.ReverseIterator + : Container extends IBidirectionalContainer + ? ReverseIterator + : unknown; - /** - * Deduct value type. - */ - export type ValueType< - Container extends Array | IBidirectionalContainer, - > = IPointer.ValueType>; + /** + * Deduct value type. + */ + export type ValueType< + Container extends Array | IBidirectionalContainer, + > = IPointer.ValueType>; } diff --git a/src/ranges/container/IForwardContainer.ts b/src/ranges/container/IForwardContainer.ts index 47791190..bd96cfee 100644 --- a/src/ranges/container/IForwardContainer.ts +++ b/src/ranges/container/IForwardContainer.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ -import { IForwardIterator } from "../../iterator/IForwardIterator"; +import { Vector } from "../../container/Vector"; import { IPointer } from "../../functional/IPointer"; import { ISize } from "../../internal/container/partial/ISize"; - -import { Vector } from "../../container/Vector"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; /** * Forward iterable container. @@ -17,48 +17,47 @@ import { Vector } from "../../container/Vector"; * @author Jeongho Nam - https://github.com/samchon */ export interface IForwardContainer< - Iterator extends IForwardIterator, Iterator>, + Iterator extends IForwardIterator, Iterator>, > extends ISize { - /** - * Iterator to the first element. - * - * @return Iterator to the first element. - */ - begin(): Iterator; + /** + * Iterator to the first element. + * + * @return Iterator to the first element. + */ + begin(): Iterator; - /** - * Iterator to the end. - * - * @return Iterator to the end. - */ - end(): Iterator; + /** + * Iterator to the end. + * + * @return Iterator to the end. + */ + end(): Iterator; } export namespace IForwardContainer { - /** - * Deduct iterator type. - */ - export type IteratorType< - Container extends Array | IForwardContainer, - > = Container extends Array - ? Vector.Iterator - : Container extends IForwardContainer - ? Iterator - : unknown; + /** + * Deduct iterator type. + */ + export type IteratorType< + Container extends Array | IForwardContainer, + > = Container extends Array + ? Vector.Iterator + : Container extends IForwardContainer + ? Iterator + : unknown; - /** - * Deduct value type. - */ - export type ValueType< - Container extends Array | IForwardContainer, - > = IPointer.ValueType>; + /** + * Deduct value type. + */ + export type ValueType | IForwardContainer> = + IPointer.ValueType>; - /** - * Deduct similar type. - */ - export type SimilarType< - Container extends Array | IForwardContainer, - > = - | Array> - | IForwardContainer, any>>; + /** + * Deduct similar type. + */ + export type SimilarType< + Container extends Array | IForwardContainer, + > = + | Array> + | IForwardContainer, any>>; } diff --git a/src/ranges/container/IRandomAccessContainer.ts b/src/ranges/container/IRandomAccessContainer.ts index e4fbe49d..0e6ef3ce 100644 --- a/src/ranges/container/IRandomAccessContainer.ts +++ b/src/ranges/container/IRandomAccessContainer.ts @@ -1,13 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ -import { IForwardContainer } from "./IForwardContainer"; -import { IRandomAccessIterator } from "../../iterator/IRandomAccessIterator"; -import { IPointer } from "../../functional/IPointer"; import { Vector } from "../../container/Vector"; +import { IPointer } from "../../functional/IPointer"; +import { IRandomAccessIterator } from "../../iterator/IRandomAccessIterator"; +import { IForwardContainer } from "./IForwardContainer"; /** * Random-access iterable container. @@ -16,28 +17,28 @@ import { Vector } from "../../container/Vector"; * @author Jeongho Nam - https://github.com/samchon */ export interface IRandomAccessContainer< - IteratorT extends IRandomAccessIterator< - IPointer.ValueType, - IteratorT - >, + IteratorT extends IRandomAccessIterator< + IPointer.ValueType, + IteratorT + >, > extends IForwardContainer {} export namespace IRandomAccessContainer { - /** - * Deduct iterator type. - */ - export type IteratorType< - Container extends Array | IRandomAccessContainer, - > = Container extends Array - ? Vector.Iterator - : Container extends IRandomAccessContainer - ? Iterator - : unknown; + /** + * Deduct iterator type. + */ + export type IteratorType< + Container extends Array | IRandomAccessContainer, + > = Container extends Array + ? Vector.Iterator + : Container extends IRandomAccessContainer + ? Iterator + : unknown; - /** - * Deduct value type. - */ - export type ValueType< - Container extends Array | IRandomAccessContainer, - > = IForwardContainer.ValueType>; + /** + * Deduct value type. + */ + export type ValueType< + Container extends Array | IRandomAccessContainer, + > = IForwardContainer.ValueType>; } diff --git a/src/ranges/index.ts b/src/ranges/index.ts index 55169ebd..50771e2e 100644 --- a/src/ranges/index.ts +++ b/src/ranges/index.ts @@ -1,4 +1,5 @@ //================================================================ + /** * Ranged Features * diff --git a/src/ranges/numeric/operations.ts b/src/ranges/numeric/operations.ts index 381ddf4d..3a3b2880 100644 --- a/src/ranges/numeric/operations.ts +++ b/src/ranges/numeric/operations.ts @@ -1,188 +1,182 @@ //================================================================ + /** * @packageDocumentation * @module std.ranges */ //================================================================ -import * as base from "../../numeric/operations"; - -import { IForwardContainer } from "../container/IForwardContainer"; -import { IForwardIterator } from "../../iterator/IForwardIterator"; - import { IPointer } from "../../functional/IPointer"; import { Writeonly } from "../../internal/functional/Writeonly"; +import { IForwardIterator } from "../../iterator/IForwardIterator"; import { begin, end } from "../../iterator/factory"; -import { plus, multiplies, minus } from "../../numeric/operators"; +import * as base from "../../numeric/operations"; +import { minus, multiplies, plus } from "../../numeric/operators"; +import { IForwardContainer } from "../container/IForwardContainer"; type UnaryTransformer< - Range extends Array | IForwardContainer, - OutputIterator extends IForwardIterator< - IPointer.ValueType, - OutputIterator - >, + Range extends Array | IForwardContainer, + OutputIterator extends IForwardIterator< + IPointer.ValueType, + OutputIterator + >, > = ( - val: IForwardContainer.ValueType, + val: IForwardContainer.ValueType, ) => IPointer.ValueType; type BinaryTransformer< - OutputIterator extends IForwardIterator< - IPointer.ValueType, - OutputIterator - >, + OutputIterator extends IForwardIterator< + IPointer.ValueType, + OutputIterator + >, > = ( - x: IPointer.ValueType, - y: IPointer.ValueType, + x: IPointer.ValueType, + y: IPointer.ValueType, ) => IPointer.ValueType; type Operator< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer = Range1, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer = Range1, > = ( - x: IForwardContainer.ValueType, - y: IForwardContainer.ValueType, + x: IForwardContainer.ValueType, + y: IForwardContainer.ValueType, ) => IForwardContainer.ValueType; /* --------------------------------------------------------- COMMON ALGORITHMS --------------------------------------------------------- */ export function iota< - Range extends Array | IForwardContainer>, + Range extends Array | IForwardContainer>, >(range: Range, value: number): void { - return base.iota(begin(range), end(range), value); + return base.iota(begin(range), end(range), value); } export function accumulate | IForwardContainer>( - range: Range, - init: IForwardContainer.ValueType, - op: Operator = plus, + range: Range, + init: IForwardContainer.ValueType, + op: Operator = plus, ): IForwardContainer.ValueType { - return base.accumulate(begin(range), end(range), init, op); + return base.accumulate(begin(range), end(range), init, op); } export function inner_product< - Range1 extends Array | IForwardContainer, - Range2 extends Array | IForwardContainer, + Range1 extends Array | IForwardContainer, + Range2 extends Array | IForwardContainer, >( - range1: Range1, - range2: Range2, - value: IForwardContainer.ValueType, - adder: Operator = plus, - multiplier: Operator = multiplies, + range1: Range1, + range2: Range2, + value: IForwardContainer.ValueType, + adder: Operator = plus, + multiplier: Operator = multiplies, ): IForwardContainer.ValueType { - return base.inner_product( - begin(range1), - end(range1), - begin(range2), - value, - adder, - multiplier, - ); + return base.inner_product( + begin(range1), + end(range1), + begin(range2), + value, + adder, + multiplier, + ); } export function adjacent_difference< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - output: OutputIterator, - subtracter: Operator = minus, + range: Range, + output: OutputIterator, + subtracter: Operator = minus, ): OutputIterator { - return base.adjacent_difference( - begin(range), - end(range), - output, - subtracter, - ); + return base.adjacent_difference(begin(range), end(range), output, subtracter); } export function partial_sum< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - output: OutputIterator, - adder: Operator = plus, + range: Range, + output: OutputIterator, + adder: Operator = plus, ): OutputIterator { - return base.partial_sum(begin(range), end(range), output, adder); + return base.partial_sum(begin(range), end(range), output, adder); } /* --------------------------------------------------------- PREFIX SUMS --------------------------------------------------------- */ export function inclusive_scan< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - output: OutputIterator, - adder: Operator = plus, - init?: IForwardContainer.ValueType, + range: Range, + output: OutputIterator, + adder: Operator = plus, + init?: IForwardContainer.ValueType, ): OutputIterator { - return base.inclusive_scan(begin(range), end(range), output, adder, init); + return base.inclusive_scan(begin(range), end(range), output, adder, init); } export function exclusive_scan< - Range extends Array | IForwardContainer, - OutputIterator extends Writeonly< - IForwardIterator, OutputIterator> - >, + Range extends Array | IForwardContainer, + OutputIterator extends Writeonly< + IForwardIterator, OutputIterator> + >, >( - range: Range, - output: OutputIterator, - init: IForwardContainer.ValueType, - adder: Operator = plus, + range: Range, + output: OutputIterator, + init: IForwardContainer.ValueType, + adder: Operator = plus, ): OutputIterator { - return base.exclusive_scan(begin(range), end(range), output, init, adder); + return base.exclusive_scan(begin(range), end(range), output, init, adder); } export function transform_inclusive_scan< - Range extends Array | IForwardContainer, - OutputIterator extends IForwardIterator< - IPointer.ValueType, - OutputIterator - >, + Range extends Array | IForwardContainer, + OutputIterator extends IForwardIterator< + IPointer.ValueType, + OutputIterator + >, >( - range: Range, - output: OutputIterator, - binary: BinaryTransformer, - unary: UnaryTransformer, - init?: IForwardContainer.ValueType, + range: Range, + output: OutputIterator, + binary: BinaryTransformer, + unary: UnaryTransformer, + init?: IForwardContainer.ValueType, ): OutputIterator { - return base.transform_inclusive_scan( - begin(range), - end(range), - output, - binary, - unary, - init, - ); + return base.transform_inclusive_scan( + begin(range), + end(range), + output, + binary, + unary, + init, + ); } export function transform_exclusive_scan< - Range extends Array | IForwardContainer, - OutputIterator extends IForwardIterator< - IPointer.ValueType, - OutputIterator - >, + Range extends Array | IForwardContainer, + OutputIterator extends IForwardIterator< + IPointer.ValueType, + OutputIterator + >, >( - range: Range, - output: OutputIterator, - init: IForwardContainer.ValueType, - binary: BinaryTransformer, - unary: UnaryTransformer, + range: Range, + output: OutputIterator, + init: IForwardContainer.ValueType, + binary: BinaryTransformer, + unary: UnaryTransformer, ): OutputIterator { - return base.transform_exclusive_scan( - begin(range), - end(range), - output, - init, - binary, - unary, - ); + return base.transform_exclusive_scan( + begin(range), + end(range), + output, + init, + binary, + unary, + ); } diff --git a/src/test/algorithm/test_binary_searches.ts b/src/test/algorithm/test_binary_searches.ts index ca401f30..ae03e503 100644 --- a/src/test/algorithm/test_binary_searches.ts +++ b/src/test/algorithm/test_binary_searches.ts @@ -1,119 +1,119 @@ import * as std from "../../index"; export function test_binary_searches(): void { - _Test_binary_search_of_atom(); - _Test_binary_search_of_pair(); + _Test_binary_search_of_atom(); + _Test_binary_search_of_pair(); } function _Test_binary_search_of_atom(): void { - const v: std.Vector = new std.Vector(); - const s: std.TreeMultiSet = new std.TreeMultiSet(); - - //---- - // FILL VALUES - //---- - // INSERT ELEMENTS - for (let i: number = 0; i < 100; ++i) { - const val: number = Math.random(); - - v.push_back(val); - s.insert(val); - } - - // SORT VECTOR - std.ranges.sort(v); - - //---- - // VALIDATE - //---- - for (let i: number = 0; i < 10000; ++i) { - const val: number = Math.random(); - - const v_it = std.ranges.equal_range(v, val); - const s_it = s.equal_range(val); - - // VALIDATE LOWER BOUND - if (v_it.first.equals(v.end()) === true) - if (s_it.first.equals(s.end()) === false) - throw new Error( - "Bug on std.lower_bound() or Set.lower_bound(); someone is out bound but the other is not.", - ); - else continue; - else if (v_it.first.value !== s_it.first.value) - throw new Error( - "Bug on std.lower_bound() or Set.lower_bound(); different value.", - ); - - // VALIDATE UPPER BOUND - if (v_it.second.equals(v.end()) === true) - if (s_it.second.equals(s.end()) === false) - throw new Error( - "Bug on std.upper_bound() or Set.upper_bound(); someone is out bound but the other is not.", - ); - else continue; - else if (v_it.second.value !== s_it.second.value) - throw new Error( - "Bug on std.upper_bound() or Set.upper_bound(); different value.", - ); - } + const v: std.Vector = new std.Vector(); + const s: std.TreeMultiSet = new std.TreeMultiSet(); + + //---- + // FILL VALUES + //---- + // INSERT ELEMENTS + for (let i: number = 0; i < 100; ++i) { + const val: number = Math.random(); + + v.push_back(val); + s.insert(val); + } + + // SORT VECTOR + std.ranges.sort(v); + + //---- + // VALIDATE + //---- + for (let i: number = 0; i < 10000; ++i) { + const val: number = Math.random(); + + const v_it = std.ranges.equal_range(v, val); + const s_it = s.equal_range(val); + + // VALIDATE LOWER BOUND + if (v_it.first.equals(v.end()) === true) + if (s_it.first.equals(s.end()) === false) + throw new Error( + "Bug on std.lower_bound() or Set.lower_bound(); someone is out bound but the other is not.", + ); + else continue; + else if (v_it.first.value !== s_it.first.value) + throw new Error( + "Bug on std.lower_bound() or Set.lower_bound(); different value.", + ); + + // VALIDATE UPPER BOUND + if (v_it.second.equals(v.end()) === true) + if (s_it.second.equals(s.end()) === false) + throw new Error( + "Bug on std.upper_bound() or Set.upper_bound(); someone is out bound but the other is not.", + ); + else continue; + else if (v_it.second.value !== s_it.second.value) + throw new Error( + "Bug on std.upper_bound() or Set.upper_bound(); different value.", + ); + } } function _Test_binary_search_of_pair(): void { - const v: std.Vector> = new std.Vector(); - const m: std.TreeMultiMap = new std.TreeMultiMap(); - - //---- - // FILL VALUES - //---- - // INSERT ELEMENTS - for (let i: number = 0; i < 100; ++i) { - const pair = std.make_pair(Math.random(), 0); - - v.push_back(pair); - m.insert(pair); - } - - // SORT VECTOR - std.ranges.sort(v, _Compare_numbers_pair); - - //---- - // VALIDATE - //---- - for (let i: number = 0; i < 10000; ++i) { - const pair = std.make_pair(Math.random(), 0); - - const v_it = std.ranges.equal_range(v, pair, _Compare_numbers_pair); - const m_it = m.equal_range(pair.first); - - // VALIDATE LOWER BOUND - if (v_it.first.equals(v.end()) === true) - if (m_it.first.equals(m.end()) === false) - throw new Error( - "Bug on std.lower_bound() or Set.lower_bound(); someone is out bound but the other is not.", - ); - else continue; - else if (v_it.first.value.first !== m_it.first.first) - throw new Error( - "Bug on std.lower_bound() or Set.lower_bound(); different value.", - ); - - // VALIDATE UPPER BOUND - if (v_it.second.equals(v.end()) === true) - if (m_it.second.equals(m.end()) === false) - throw new Error( - "Bug on std.upper_bound() or Set.upper_bound(); someone is out bound but the other is not.", - ); - else continue; - else if (v_it.second.value.first !== m_it.second.first) - throw new Error( - "Bug on std.upper_bound() or Set.upper_bound(); different value.", - ); - } + const v: std.Vector> = new std.Vector(); + const m: std.TreeMultiMap = new std.TreeMultiMap(); + + //---- + // FILL VALUES + //---- + // INSERT ELEMENTS + for (let i: number = 0; i < 100; ++i) { + const pair = std.make_pair(Math.random(), 0); + + v.push_back(pair); + m.insert(pair); + } + + // SORT VECTOR + std.ranges.sort(v, _Compare_numbers_pair); + + //---- + // VALIDATE + //---- + for (let i: number = 0; i < 10000; ++i) { + const pair = std.make_pair(Math.random(), 0); + + const v_it = std.ranges.equal_range(v, pair, _Compare_numbers_pair); + const m_it = m.equal_range(pair.first); + + // VALIDATE LOWER BOUND + if (v_it.first.equals(v.end()) === true) + if (m_it.first.equals(m.end()) === false) + throw new Error( + "Bug on std.lower_bound() or Set.lower_bound(); someone is out bound but the other is not.", + ); + else continue; + else if (v_it.first.value.first !== m_it.first.first) + throw new Error( + "Bug on std.lower_bound() or Set.lower_bound(); different value.", + ); + + // VALIDATE UPPER BOUND + if (v_it.second.equals(v.end()) === true) + if (m_it.second.equals(m.end()) === false) + throw new Error( + "Bug on std.upper_bound() or Set.upper_bound(); someone is out bound but the other is not.", + ); + else continue; + else if (v_it.second.value.first !== m_it.second.first) + throw new Error( + "Bug on std.upper_bound() or Set.upper_bound(); different value.", + ); + } } function _Compare_numbers_pair( - x: std.Pair, - y: std.Pair, + x: std.Pair, + y: std.Pair, ): boolean { - return x.first < y.first; + return x.first < y.first; } diff --git a/src/test/algorithm/test_heaps.ts b/src/test/algorithm/test_heaps.ts index a33a974a..35a83e86 100644 --- a/src/test/algorithm/test_heaps.ts +++ b/src/test/algorithm/test_heaps.ts @@ -2,54 +2,54 @@ import * as std from "../../index"; import { Generator } from "../internal/Generator"; export function test_heaps(): void { - for (let i: number = 0; i < 100; ++i) { - const elems: std.Vector = Generator.fill(new std.Vector(), 100); - std.ranges.make_heap(elems); + for (let i: number = 0; i < 100; ++i) { + const elems: std.Vector = Generator.fill(new std.Vector(), 100); + std.ranges.make_heap(elems); - if (std.ranges.is_heap(elems) === false) - throw new Error("Bug on std.push_heap() or std.is_heap()"); + if (std.ranges.is_heap(elems) === false) + throw new Error("Bug on std.push_heap() or std.is_heap()"); - std.ranges.sort_heap(elems); - if (std.ranges.is_sorted(elems) === false) - throw new Error("Bug on std.pop_heap()"); - } + std.ranges.sort_heap(elems); + if (std.ranges.is_sorted(elems) === false) + throw new Error("Bug on std.pop_heap()"); + } - _Test_c_plus_plus(); - _Test_cpp_reference(); + _Test_c_plus_plus(); + _Test_cpp_reference(); } function _Test_c_plus_plus(): void { - const v: std.Vector = new std.Vector([10, 20, 30, 5, 15]); + const v: std.Vector = new std.Vector([10, 20, 30, 5, 15]); - std.ranges.make_heap(v); - if (v.front() !== 30 || std.ranges.is_heap(v) === false) - throw new Error("Bug on std.make_heap()"); + std.ranges.make_heap(v); + if (v.front() !== 30 || std.ranges.is_heap(v) === false) + throw new Error("Bug on std.make_heap()"); - std.ranges.pop_heap(v); - v.pop_back(); - if (v.front() !== 20) throw new Error("Bug on std.pop_heap()"); + std.ranges.pop_heap(v); + v.pop_back(); + if (v.front() !== 20) throw new Error("Bug on std.pop_heap()"); - v.push_back(99); - std.ranges.push_heap(v); - if (v.front() !== 99) throw new Error("Bug on std.push_heap()"); + v.push_back(99); + std.ranges.push_heap(v); + if (v.front() !== 99) throw new Error("Bug on std.push_heap()"); - std.ranges.sort_heap(v); - if (std.ranges.is_sorted(v) === false) - throw new Error("Bug on std.sort_heap()"); + std.ranges.sort_heap(v); + if (std.ranges.is_sorted(v) === false) + throw new Error("Bug on std.sort_heap()"); } function _Test_cpp_reference(): void { - const v: std.Vector = new std.Vector(); - v.push(3, 1, 4, 1, 5, 9); + const v: std.Vector = new std.Vector(); + v.push(3, 1, 4, 1, 5, 9); - std.ranges.make_heap(v); - if (std.ranges.equal(v, [9, 5, 4, 1, 1, 3]) === false) - throw new Error("Bug on std.make_heap()"); + std.ranges.make_heap(v); + if (std.ranges.equal(v, [9, 5, 4, 1, 1, 3]) === false) + throw new Error("Bug on std.make_heap()"); - std.ranges.pop_heap(v); - if (v.back() !== 9) throw new Error("Bug on std.pop_heap()"); + std.ranges.pop_heap(v); + if (v.back() !== 9) throw new Error("Bug on std.pop_heap()"); - v.pop_back(); - if (std.ranges.equal(v, [5, 3, 4, 1, 1]) === false) - throw new Error("Bug on std.pop_heap() & Vector.pop()"); + v.pop_back(); + if (std.ranges.equal(v, [5, 3, 4, 1, 1]) === false) + throw new Error("Bug on std.pop_heap() & Vector.pop()"); } diff --git a/src/test/algorithm/test_is_unique.ts b/src/test/algorithm/test_is_unique.ts index f2e513f5..a0a37663 100644 --- a/src/test/algorithm/test_is_unique.ts +++ b/src/test/algorithm/test_is_unique.ts @@ -1,13 +1,13 @@ import * as std from "../../index"; export function test_is_unique(): void { - const elements: number[] = []; - for (let i: number = 0; i < 10; ++i) elements.push(i); + const elements: number[] = []; + for (let i: number = 0; i < 10; ++i) elements.push(i); - if (std.ranges.is_unique(elements) === false) - throw new Error("Bug on std.is_unique(): must be true but false."); + if (std.ranges.is_unique(elements) === false) + throw new Error("Bug on std.is_unique(): must be true but false."); - elements.push(9); - if (std.ranges.is_unique(elements) === true) - throw new Error("Bug on std.is_unique(): must be false but true."); + elements.push(9); + if (std.ranges.is_unique(elements) === true) + throw new Error("Bug on std.is_unique(): must be false but true."); } diff --git a/src/test/algorithm/test_iterations.ts b/src/test/algorithm/test_iterations.ts index 3a23f26a..4edc195b 100644 --- a/src/test/algorithm/test_iterations.ts +++ b/src/test/algorithm/test_iterations.ts @@ -4,101 +4,94 @@ const SIZE = 1000; const MID = 561; export function test_iterations(): void { - _Test_for_of_iterations(); - _Test_union_of_iterations(); - _Test_equals(); - _Test_mismatch(); - _Test_count(); - _Test_lexicographical_compare(); + _Test_for_of_iterations(); + _Test_union_of_iterations(); + _Test_equals(); + _Test_mismatch(); + _Test_count(); + _Test_lexicographical_compare(); } function _Test_for_of_iterations(): void { - const items = new std.Vector(); - items.assign(1000, 1.5); + const items = new std.Vector(); + items.assign(1000, 1.5); - let sum: number = 0; - const fn = (val: number): void => { - sum += val; - }; + let sum: number = 0; + const fn = (val: number): void => { + sum += val; + }; - std.ranges.for_each(items, fn); - std.for_each_n(items.begin(), items.size(), fn); + std.ranges.for_each(items, fn); + std.for_each_n(items.begin(), items.size(), fn); - if (sum !== 1.5 * 1000 * 2) - throw new Error("Bug on std.for_each() or std.for_each_n()"); + if (sum !== 1.5 * 1000 * 2) + throw new Error("Bug on std.for_each() or std.for_each_n()"); } function _Test_union_of_iterations(): void { - const items = new std.Vector([2, 3, 4]); - const flags = new std.Vector([ - std.ranges.all_of(items, (val) => val > 1.0), - std.ranges.any_of(items, (val) => val === 2.0), - std.ranges.none_of(items, (val) => val !== Math.floor(val)), - ]); - - const ret: boolean = std.ranges.all_of(flags, (val) => val); - if (ret === false) - throw new Error("Bug on one of them: all_of(), any_of() or none_of()"); + const items = new std.Vector([2, 3, 4]); + const flags = new std.Vector([ + std.ranges.all_of(items, (val) => val > 1.0), + std.ranges.any_of(items, (val) => val === 2.0), + std.ranges.none_of(items, (val) => val !== Math.floor(val)), + ]); + + const ret: boolean = std.ranges.all_of(flags, (val) => val); + if (ret === false) + throw new Error("Bug on one of them: all_of(), any_of() or none_of()"); } function _Test_equals(): void { - const v1 = new std.Vector(); - const v2 = new std.Vector(); + const v1 = new std.Vector(); + const v2 = new std.Vector(); - for (let i: number = 0; i < SIZE; ++i) v1.push_back(Math.random()); - v2.assign(v1.begin(), v1.end()); + for (let i: number = 0; i < SIZE; ++i) v1.push_back(Math.random()); + v2.assign(v1.begin(), v1.end()); - for (let i: number = MID; i < SIZE; ++i) v2.set(i, v2.at(i) * 100.0); + for (let i: number = MID; i < SIZE; ++i) v2.set(i, v2.at(i) * 100.0); - if (std.equal(v1.begin(), v1.begin().advance(MID), v2.begin()) === false) - throw new Error("Bug on std.equal(); true -> false"); - else if (std.ranges.equal(v1, v2) === true) - throw new Error("Bug on std.equal(); false -> true"); + if (std.equal(v1.begin(), v1.begin().advance(MID), v2.begin()) === false) + throw new Error("Bug on std.equal(); true -> false"); + else if (std.ranges.equal(v1, v2) === true) + throw new Error("Bug on std.equal(); false -> true"); } function _Test_lexicographical_compare(): void { - const v1 = new std.Vector([1, 1, 2, 3]); - const v2 = new std.Vector([1, 1, 3, 3]); - - if ( - std.lexicographical_compare( - v1.begin(), - v1.end(), - v2.begin(), - v2.end(), - ) === false - ) - throw new Error("Bug on std.lexicographical_compare()"); + const v1 = new std.Vector([1, 1, 2, 3]); + const v2 = new std.Vector([1, 1, 3, 3]); + + if ( + std.lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end()) === + false + ) + throw new Error("Bug on std.lexicographical_compare()"); } function _Test_mismatch(): void { - const v1 = new std.Vector(); - const v2 = new std.Vector(); + const v1 = new std.Vector(); + const v2 = new std.Vector(); - for (let i: number = 0; i < SIZE; ++i) v1.push_back(Math.random()); - v2.assign(v1.begin(), v1.end()); + for (let i: number = 0; i < SIZE; ++i) v1.push_back(Math.random()); + v2.assign(v1.begin(), v1.end()); - v2.set(MID, -90); + v2.set(MID, -90); - const pair = std.mismatch(v1.begin(), v1.end(), v2.begin()); - if ( - pair.first.index() !== pair.second.index() || - pair.first.index() !== MID - ) - throw new Error("Bug on std.mismatch()"); + const pair = std.mismatch(v1.begin(), v1.end(), v2.begin()); + if (pair.first.index() !== pair.second.index() || pair.first.index() !== MID) + throw new Error("Bug on std.mismatch()"); } function _Test_count(): void { - const v = new std.Vector(); - for (let i: number = 0; i < SIZE; ++i) v.push_back(Math.random()); + const v = new std.Vector(); + for (let i: number = 0; i < SIZE; ++i) v.push_back(Math.random()); - const fn = function (val: number): boolean { - return val >= 0.5; - }; + const fn = function (val: number): boolean { + return val >= 0.5; + }; - let cnt: number = 0; - for (const val of v) if (fn(val) === true) ++cnt; + let cnt: number = 0; + for (const val of v) if (fn(val) === true) ++cnt; - if (std.count_if(v.begin(), v.end(), fn) !== cnt) - throw new Error("Bug on std.count_if()"); + if (std.count_if(v.begin(), v.end(), fn) !== cnt) + throw new Error("Bug on std.count_if()"); } diff --git a/src/test/algorithm/test_mathmatics.ts b/src/test/algorithm/test_mathmatics.ts index a24a3b7e..c886a159 100644 --- a/src/test/algorithm/test_mathmatics.ts +++ b/src/test/algorithm/test_mathmatics.ts @@ -1,36 +1,36 @@ import * as std from "../../index"; export function test_mathmatics(): void { - _Test_min_max(); - _Test_permutations(); + _Test_min_max(); + _Test_permutations(); } function _Test_min_max(): void { - const v = new std.Vector(); - for (let i: number = 0; i < 1000; ++i) v.push_back(Math.random()); + const v = new std.Vector(); + for (let i: number = 0; i < 1000; ++i) v.push_back(Math.random()); - const pair = std.minmax_element(v.begin(), v.end()); - const min = Math.min(...v.data()); - const max = Math.max(...v.data()); + const pair = std.minmax_element(v.begin(), v.end()); + const min = Math.min(...v.data()); + const max = Math.max(...v.data()); - if (min !== pair.first.value || max !== pair.second.value) - throw new Error("Bug on std.minmax_element()."); + if (min !== pair.first.value || max !== pair.second.value) + throw new Error("Bug on std.minmax_element()."); } function _Test_permutations(): void { - const x = new std.Vector([0, 1, 2, 3]); - const y = new std.Vector([3, 2, 1, 0]); + const x = new std.Vector([0, 1, 2, 3]); + const y = new std.Vector([3, 2, 1, 0]); - if (std.ranges.is_permutation(x, y) === false) - throw new Error("Bug on std.is_permutation()."); + if (std.ranges.is_permutation(x, y) === false) + throw new Error("Bug on std.is_permutation()."); - // NEXT_PERMUTATION - let cnt: number = 1; - while (std.ranges.next_permutation(x) === true) ++cnt; - if (cnt !== 4 * 3 * 2) throw new Error("Bug on std.next_permutation()."); + // NEXT_PERMUTATION + let cnt: number = 1; + while (std.ranges.next_permutation(x) === true) ++cnt; + if (cnt !== 4 * 3 * 2) throw new Error("Bug on std.next_permutation()."); - // PREV_PERMUTATION - cnt = 1; - while (std.ranges.prev_permutation(y) === true) ++cnt; - if (cnt !== 4 * 3 * 2) throw new Error("Bug on std.prev_permutation()."); + // PREV_PERMUTATION + cnt = 1; + while (std.ranges.prev_permutation(y) === true) ++cnt; + if (cnt !== 4 * 3 * 2) throw new Error("Bug on std.prev_permutation()."); } diff --git a/src/test/algorithm/test_merges.ts b/src/test/algorithm/test_merges.ts index b642a26c..e0122c1f 100644 --- a/src/test/algorithm/test_merges.ts +++ b/src/test/algorithm/test_merges.ts @@ -1,106 +1,105 @@ import * as std from "../../index"; - import { Generator } from "../internal/Generator"; export function test_merges(): void { - _Test_merge(); - _Test_inplace_merge(); - _Test_includes(); - _Test_set_union(); - _Test_set_intersection(); - _Test_set_difference(); - _Test_set_symmetric_difference(); + _Test_merge(); + _Test_inplace_merge(); + _Test_includes(); + _Test_set_union(); + _Test_set_intersection(); + _Test_set_difference(); + _Test_set_symmetric_difference(); } function _Test_merge(): void { - const v1: std.Vector = Generator.arrange(new std.Vector(), 100); - const v2: std.Deque = Generator.arrange(new std.Deque(), 50); - - const out: std.List = new std.List(); - std.ranges.merge(v1, v2, std.back_inserter(out)); - - const solution: std.TreeMultiSet = new std.TreeMultiSet([ - ...v1, - ...v2, - ]); - if (std.ranges.equal(out, solution) === false) - throw new Error("Bug on std.merge()"); + const v1: std.Vector = Generator.arrange(new std.Vector(), 100); + const v2: std.Deque = Generator.arrange(new std.Deque(), 50); + + const out: std.List = new std.List(); + std.ranges.merge(v1, v2, std.back_inserter(out)); + + const solution: std.TreeMultiSet = new std.TreeMultiSet([ + ...v1, + ...v2, + ]); + if (std.ranges.equal(out, solution) === false) + throw new Error("Bug on std.merge()"); } function _Test_inplace_merge(): void { - const v: std.Vector = Generator.fill(new std.Vector(), 400); - const pos: std.Vector.Iterator = v.nth(200); + const v: std.Vector = Generator.fill(new std.Vector(), 400); + const pos: std.Vector.Iterator = v.nth(200); - std.sort(v.begin(), pos); - std.sort(pos, v.end()); + std.sort(v.begin(), pos); + std.sort(pos, v.end()); - std.ranges.inplace_merge(v, pos); - if (std.ranges.is_sorted(v) === false) - throw new Error("Bug on std.inplace_merge()"); + std.ranges.inplace_merge(v, pos); + if (std.ranges.is_sorted(v) === false) + throw new Error("Bug on std.inplace_merge()"); } function _Test_includes(): void { - const v1: std.Vector = Generator.arrange(new std.Vector(), 100); - const v2: std.Vector = std.Vector.wrap( - v1.data().slice(std.randint(10, 30), std.randint(10, 30)), - ); + const v1: std.Vector = Generator.arrange(new std.Vector(), 100); + const v2: std.Vector = std.Vector.wrap( + v1.data().slice(std.randint(10, 30), std.randint(10, 30)), + ); - if (std.ranges.includes(v1, v2) === false) - throw new Error("Bug on std.includes()"); + if (std.ranges.includes(v1, v2) === false) + throw new Error("Bug on std.includes()"); } function _Test_set_union(): void { - const v1: std.TreeSet = Generator.fill(new std.TreeSet(), 200); - const v2: std.TreeSet = Generator.fill(new std.TreeSet(), 200); + const v1: std.TreeSet = Generator.fill(new std.TreeSet(), 200); + const v2: std.TreeSet = Generator.fill(new std.TreeSet(), 200); - const out: std.List = new std.List(); - std.ranges.set_union(v1, v2, std.back_inserter(out)); + const out: std.List = new std.List(); + std.ranges.set_union(v1, v2, std.back_inserter(out)); - const solution: std.TreeSet = new std.TreeSet([...v1, ...v2]); - if (std.ranges.equal(out, solution) === false) - throw new Error("Bug on std.set_union()"); + const solution: std.TreeSet = new std.TreeSet([...v1, ...v2]); + if (std.ranges.equal(out, solution) === false) + throw new Error("Bug on std.set_union()"); } function _Test_set_intersection(): void { - const v1: std.TreeSet = Generator.fill(new std.TreeSet(), 200); - const v2: std.TreeSet = Generator.fill(new std.TreeSet(), 200); + const v1: std.TreeSet = Generator.fill(new std.TreeSet(), 200); + const v2: std.TreeSet = Generator.fill(new std.TreeSet(), 200); - const out: std.Vector = new std.Vector(); - std.ranges.set_intersection(v1, v2, std.back_inserter(out)); + const out: std.Vector = new std.Vector(); + std.ranges.set_intersection(v1, v2, std.back_inserter(out)); - const solution: std.Deque = new std.Deque(); - for (const elem of v1) if (v2.has(elem) === true) solution.push_back(elem); + const solution: std.Deque = new std.Deque(); + for (const elem of v1) if (v2.has(elem) === true) solution.push_back(elem); - if (std.ranges.equal(out, solution) === false) - throw new Error("Bug on std.set_intersection()"); + if (std.ranges.equal(out, solution) === false) + throw new Error("Bug on std.set_intersection()"); } function _Test_set_difference(): void { - const v1: std.TreeSet = Generator.fill(new std.TreeSet(), 200); - const v2: std.TreeSet = Generator.fill(new std.TreeSet(), 200); + const v1: std.TreeSet = Generator.fill(new std.TreeSet(), 200); + const v2: std.TreeSet = Generator.fill(new std.TreeSet(), 200); - const out: std.Deque = new std.Deque(); - std.ranges.set_difference(v1, v2, std.back_inserter(out)); + const out: std.Deque = new std.Deque(); + std.ranges.set_difference(v1, v2, std.back_inserter(out)); - const solution: std.Vector = new std.Vector(); - for (const elem of v1) if (v2.has(elem) === false) solution.push_back(elem); + const solution: std.Vector = new std.Vector(); + for (const elem of v1) if (v2.has(elem) === false) solution.push_back(elem); - if (std.ranges.equal(out, solution) === false) - throw new Error("Bug on std.set_difference()"); + if (std.ranges.equal(out, solution) === false) + throw new Error("Bug on std.set_difference()"); } function _Test_set_symmetric_difference(): void { - const v1: std.TreeSet = Generator.fill(new std.TreeSet(), 200); - const v2: std.TreeSet = Generator.fill(new std.TreeSet(), 200); + const v1: std.TreeSet = Generator.fill(new std.TreeSet(), 200); + const v2: std.TreeSet = Generator.fill(new std.TreeSet(), 200); - const out: std.List = new std.List(); - std.ranges.set_symmetric_difference(v1, v2, std.back_inserter(out)); + const out: std.List = new std.List(); + std.ranges.set_symmetric_difference(v1, v2, std.back_inserter(out)); - const solution: std.Deque = new std.Deque(); - for (const elem of v1) if (v2.has(elem) === false) solution.push_back(elem); - for (const elem of v2) if (v1.has(elem) === false) solution.push_back(elem); - std.ranges.sort(solution); + const solution: std.Deque = new std.Deque(); + for (const elem of v1) if (v2.has(elem) === false) solution.push_back(elem); + for (const elem of v2) if (v1.has(elem) === false) solution.push_back(elem); + std.ranges.sort(solution); - if (std.ranges.equal(out, solution) === false) - throw new Error("Bug on std.set_symmetric_difference()"); + if (std.ranges.equal(out, solution) === false) + throw new Error("Bug on std.set_symmetric_difference()"); } diff --git a/src/test/algorithm/test_modifiers.ts b/src/test/algorithm/test_modifiers.ts index 4eb59c1b..e39838f2 100644 --- a/src/test/algorithm/test_modifiers.ts +++ b/src/test/algorithm/test_modifiers.ts @@ -1,53 +1,52 @@ import * as std from "../../index"; export function test_modifiers(): void { - _Test_removes(); - _Test_replaces(); + _Test_removes(); + _Test_replaces(); - _Test_uniques(); - _Test_rotate(); + _Test_uniques(); + _Test_rotate(); } function _Test_removes(): void { - const v: std.Vector = _Create_sample(); - v.erase(std.remove(v.begin(), v.end(), 2), v.end()); + const v: std.Vector = _Create_sample(); + v.erase(std.remove(v.begin(), v.end(), 2), v.end()); - const it = std.find(v.begin(), v.end(), 2); - if (it.equals(v.end()) === false) throw new Error("Bug on std.remove()."); + const it = std.find(v.begin(), v.end(), 2); + if (it.equals(v.end()) === false) throw new Error("Bug on std.remove()."); } function _Test_replaces(): void { - const v: std.Vector = _Create_sample(); - std.replace(v.begin(), v.end(), 2, 4); + const v: std.Vector = _Create_sample(); + std.replace(v.begin(), v.end(), 2, 4); - const it = std.find(v.begin(), v.end(), 2); - if (it.equals(v.end()) === false) throw new Error("Bug on std.replace()."); + const it = std.find(v.begin(), v.end(), 2); + if (it.equals(v.end()) === false) throw new Error("Bug on std.replace()."); } function _Test_uniques(): void { - const l: std.List = new std.List(); - for (let i: number = 0; i < 1000; ++i) - l.push_back(Math.floor(Math.random() * 50)); + const l: std.List = new std.List(); + for (let i: number = 0; i < 1000; ++i) + l.push_back(Math.floor(Math.random() * 50)); - l.sort(); - const v = new std.Vector(l.begin(), l.end()); + l.sort(); + const v = new std.Vector(l.begin(), l.end()); - l.unique(); - v.erase(std.unique(v.begin(), v.end()), v.end()); + l.unique(); + v.erase(std.unique(v.begin(), v.end()), v.end()); - if (std.equal(v.begin(), v.end(), l.begin()) === false) - throw new Error("Bug on std.unique()."); + if (std.equal(v.begin(), v.end(), l.begin()) === false) + throw new Error("Bug on std.unique()."); } function _Test_rotate(): void { - const x: std.Vector = new std.Vector([0, 1, 2, 3, 4, 5]); - const y: std.Vector = new std.Vector([3, 4, 5, 0, 1, 2]); + const x: std.Vector = new std.Vector([0, 1, 2, 3, 4, 5]); + const y: std.Vector = new std.Vector([3, 4, 5, 0, 1, 2]); - std.ranges.rotate(x, x.nth(3)); + std.ranges.rotate(x, x.nth(3)); - if (std.ranges.equal(x, y) === false) - throw new Error("Bug on std.rotate()."); + if (std.ranges.equal(x, y) === false) throw new Error("Bug on std.rotate()."); } function _Create_sample(): std.Vector { - return new std.Vector([1, 2, 2, 3, 3, 3]); + return new std.Vector([1, 2, 2, 3, 3, 3]); } diff --git a/src/test/algorithm/test_partitions.ts b/src/test/algorithm/test_partitions.ts index f148fb6a..43040f35 100644 --- a/src/test/algorithm/test_partitions.ts +++ b/src/test/algorithm/test_partitions.ts @@ -1,17 +1,17 @@ import * as std from "../../index"; export function test_partitions(): void { - const v = new std.Vector(); - for (let i: number = 0; i < 1000; ++i) v.push_back(i); + const v = new std.Vector(); + for (let i: number = 0; i < 1000; ++i) v.push_back(i); - std.ranges.partition(v, _Pred); + std.ranges.partition(v, _Pred); - if (std.all_of(v.begin(), v.begin().advance(500), _Pred) === false) - throw new Error("Bug on std.partition()."); - else if (std.ranges.is_partitioned(v, _Pred) === false) - throw new Error("Bug on std.is_partitioned()."); + if (std.all_of(v.begin(), v.begin().advance(500), _Pred) === false) + throw new Error("Bug on std.partition()."); + else if (std.ranges.is_partitioned(v, _Pred) === false) + throw new Error("Bug on std.is_partitioned()."); } function _Pred(val: number): boolean { - return val < 500; + return val < 500; } diff --git a/src/test/algorithm/test_randoms.ts b/src/test/algorithm/test_randoms.ts index 73654c16..c33e42d5 100644 --- a/src/test/algorithm/test_randoms.ts +++ b/src/test/algorithm/test_randoms.ts @@ -1,44 +1,44 @@ import * as std from "../../index"; export function test_randoms(): void { - _Test_rand_ints(); - _Test_samples(); + _Test_rand_ints(); + _Test_samples(); } function _Test_rand_ints(): void { - for (let i: number = 0; i < 100; ++i) { - let x: number = Math.floor(Math.random() * 100); - let y: number = Math.floor(Math.random() * 100); + for (let i: number = 0; i < 100; ++i) { + let x: number = Math.floor(Math.random() * 100); + let y: number = Math.floor(Math.random() * 100); - if (x > y) [x, y] = [y, x]; + if (x > y) [x, y] = [y, x]; - const rand: number = std.randint(x, y); - if (rand < x || rand > y) - throw new Error("Bug on std.experimantal.randint()."); - } + const rand: number = std.randint(x, y); + if (rand < x || rand > y) + throw new Error("Bug on std.experimantal.randint()."); + } } function _Test_samples(): void { - for (let i: number = 0; i < 100; ++i) { - const size: number = std.randint(10, 100); - const populations: std.Vector = _Generate_populations(size); + for (let i: number = 0; i < 100; ++i) { + const size: number = std.randint(10, 100); + const populations: std.Vector = _Generate_populations(size); - const n: number = Math.min(size, std.randint(5, 20)); - const samples: std.Vector = new std.Vector(); + const n: number = Math.min(size, std.randint(5, 20)); + const samples: std.Vector = new std.Vector(); - std.ranges.sample(populations, std.back_inserter(samples), n); - if (std.ranges.is_sorted(samples) === false) - throw new Error("Bug on std.sample(); Elements are not sorted."); + std.ranges.sample(populations, std.back_inserter(samples), n); + if (std.ranges.is_sorted(samples) === false) + throw new Error("Bug on std.sample(); Elements are not sorted."); - samples.erase(std.ranges.unique(samples), samples.end()); - if (samples.size() !== n) - throw new Error("Bug on std.sample(); Elements are not unique."); - } + samples.erase(std.ranges.unique(samples), samples.end()); + if (samples.size() !== n) + throw new Error("Bug on std.sample(); Elements are not unique."); + } } function _Generate_populations(size: number): std.Vector { - const ret: std.Vector = new std.Vector(size, 0); - for (let i: number = 0; i < ret.size(); ++i) ret.set(i, i); + const ret: std.Vector = new std.Vector(size, 0); + for (let i: number = 0; i < ret.size(); ++i) ret.set(i, i); - return ret; + return ret; } diff --git a/src/test/algorithm/test_sortings.ts b/src/test/algorithm/test_sortings.ts index 996c12ab..2ae4da42 100644 --- a/src/test/algorithm/test_sortings.ts +++ b/src/test/algorithm/test_sortings.ts @@ -1,55 +1,54 @@ import * as std from "../../index"; - import { Cube } from "../internal/Cube"; export function test_sortings(): void { - _Test_atomic_sorting(); - _Test_object_sorting(); + _Test_atomic_sorting(); + _Test_object_sorting(); } function _Test_atomic_sorting(): void { - const array: number[] = []; - for (let i: number = 1; i <= 15; ++i) - for (let j: number = 0; j < 3; ++j) array.push(i); + const array: number[] = []; + for (let i: number = 1; i <= 15; ++i) + for (let j: number = 0; j < 3; ++j) array.push(i); - std.ranges.shuffle(array); - std.ranges.stable_sort(array); + std.ranges.shuffle(array); + std.ranges.stable_sort(array); - if (std.ranges.is_sorted(array) === false) - throw new Error("Bug on std.stable_sort()"); + if (std.ranges.is_sorted(array) === false) + throw new Error("Bug on std.stable_sort()"); } function _Test_object_sorting(): void { - //---- - // CONSTRUCT ITEMS - //---- - const cubes: std.Deque = new std.Deque(); - for (let i: number = 0; i < 1000; ++i) cubes.push_back(new Cube()); - - //---- - // SORT BY Cube.less - //---- - // DO SORT - std.ranges.sort(cubes); - - // VALIDATION - if (std.ranges.is_sorted(cubes) === false) - throw new Error("Bug on std.sort() with IComparable.less()"); - - //---- - // SORT BY inline function - //---- - // DECLARE INLINE FUNCTION - const inline_function = (cx: Cube, cy: Cube) => { - if (cx.x !== cy.x) return cx.x < cy.x; - else if (cx.y !== cy.y) return cx.y < cy.y; - else return cx.z < cy.z; - }; - - // DO SORT - std.ranges.sort(cubes, inline_function); - - // VALIDATION - if (std.ranges.is_sorted(cubes, inline_function) === false) - throw new Error("Bug on std.sort() with parametric comparator"); + //---- + // CONSTRUCT ITEMS + //---- + const cubes: std.Deque = new std.Deque(); + for (let i: number = 0; i < 1000; ++i) cubes.push_back(new Cube()); + + //---- + // SORT BY Cube.less + //---- + // DO SORT + std.ranges.sort(cubes); + + // VALIDATION + if (std.ranges.is_sorted(cubes) === false) + throw new Error("Bug on std.sort() with IComparable.less()"); + + //---- + // SORT BY inline function + //---- + // DECLARE INLINE FUNCTION + const inline_function = (cx: Cube, cy: Cube) => { + if (cx.x !== cy.x) return cx.x < cy.x; + else if (cx.y !== cy.y) return cx.y < cy.y; + else return cx.z < cy.z; + }; + + // DO SORT + std.ranges.sort(cubes, inline_function); + + // VALIDATION + if (std.ranges.is_sorted(cubes, inline_function) === false) + throw new Error("Bug on std.sort() with parametric comparator"); } diff --git a/src/test/container/test_adaptors.ts b/src/test/container/test_adaptors.ts index 82812753..d371e3c0 100644 --- a/src/test/container/test_adaptors.ts +++ b/src/test/container/test_adaptors.ts @@ -1,75 +1,75 @@ import * as std from "../../index"; export function test_priority_queue(): void { - const adaptor: std.PriorityQueue = new std.PriorityQueue(); + const adaptor: std.PriorityQueue = new std.PriorityQueue(); - const elements: number[] = []; - for (let i: number = 0; i < 10; ++i) - for (let j: number = 0; j < 4; ++j) adaptor.push(i); - std.ranges.shuffle(elements); + const elements: number[] = []; + for (let i: number = 0; i < 10; ++i) + for (let j: number = 0; j < 4; ++j) adaptor.push(i); + std.ranges.shuffle(elements); - for (let i = 0; i < 10; ++i) adaptor.pop(); + for (let i = 0; i < 10; ++i) adaptor.pop(); - while (elements.length !== 0) { - const index: number = std.randint(0, elements.length - 1); - const value: number = elements[index]; + while (elements.length !== 0) { + const index: number = std.randint(0, elements.length - 1); + const value: number = elements[index]; - adaptor.push(value); - elements.splice(index, 1); - } + adaptor.push(value); + elements.splice(index, 1); + } - let previous: number = 1000; - while (adaptor.empty() === false) { - if (previous < adaptor.top()) - throw new Error( - "Bug on PriorityQueue: elements are not reversly sorted - " + - previous.toString() + - " < " + - adaptor.top().toString(), - ); + let previous: number = 1000; + while (adaptor.empty() === false) { + if (previous < adaptor.top()) + throw new Error( + "Bug on PriorityQueue: elements are not reversly sorted - " + + previous.toString() + + " < " + + adaptor.top().toString(), + ); - previous = adaptor.top(); - adaptor.pop(); - } + previous = adaptor.top(); + adaptor.pop(); + } } export function test_adaptors(): void { - // CONSTRUCT ADAPTOR CONATINERS - const queue = _Construct_adaptor(new std.Queue()); - const stack = _Construct_adaptor(new std.Stack()); + // CONSTRUCT ADAPTOR CONATINERS + const queue = _Construct_adaptor(new std.Queue()); + const stack = _Construct_adaptor(new std.Stack()); - // VALIDATE QUEUE - const queue_items: number[] = []; - while (queue.empty() === false) { - queue_items.push(queue.front()); - queue.pop(); - } - _Validate_adaptor_items(queue_items, [0, 1, 2, 3, 4]); + // VALIDATE QUEUE + const queue_items: number[] = []; + while (queue.empty() === false) { + queue_items.push(queue.front()); + queue.pop(); + } + _Validate_adaptor_items(queue_items, [0, 1, 2, 3, 4]); - // VALIDATE STACK - const stack_items: number[] = []; - while (stack.empty() === false) { - stack_items.push(stack.top()); - stack.pop(); - } - _Validate_adaptor_items(stack_items, queue_items.reverse()); + // VALIDATE STACK + const stack_items: number[] = []; + while (stack.empty() === false) { + stack_items.push(stack.top()); + stack.pop(); + } + _Validate_adaptor_items(stack_items, queue_items.reverse()); } function _Construct_adaptor(adaptor: T): T { - for (let i: number = 0; i < 5; ++i) adaptor.push(i); + for (let i: number = 0; i < 5; ++i) adaptor.push(i); - return adaptor; + return adaptor; } function _Validate_adaptor_items(items: number[], answer: number[]): void { - if (items.length !== answer.length) - throw new std.DomainError("Number of elements are wrong."); + if (items.length !== answer.length) + throw new std.DomainError("Number of elements are wrong."); - for (let i: number = 0; i < items.length; ++i) - if (items[i] !== answer[i]) - throw new std.DomainError("Wrong element is inserted in."); + for (let i: number = 0; i < items.length; ++i) + if (items[i] !== answer[i]) + throw new std.DomainError("Wrong element is inserted in."); } interface IAdaptor { - push(val: number): void; + push(val: number): void; } diff --git a/src/test/container/test_associatives.ts b/src/test/container/test_associatives.ts index 681c487d..bdb389e5 100644 --- a/src/test/container/test_associatives.ts +++ b/src/test/container/test_associatives.ts @@ -1,367 +1,364 @@ import * as std from "../../index"; - import { Atomic } from "../internal/Atomic"; export function test_associatives(): void { - //---- - // SET-CONTAINERS - //---- - // UNIQUE-SETS - _Test_unique_set(new std.HashSet>()); - _Test_unique_set(new std.TreeSet>()); - _Test_unique_set(new std.experimental.FlatSet>()); - - // MULTI-SETS - _Test_multi_set(new std.HashMultiSet>()); - _Test_multi_set(new std.TreeMultiSet>()); - _Test_multi_set(new std.experimental.FlatMultiSet>()); - - //---- - // MAP-CONTAINERS - //---- - // UNIQUE-MAPS - _Test_unique_map(new std.HashMap, number>()); - _Test_unique_map(new std.TreeMap, number>()); - _Test_unique_map(new std.experimental.FlatMap, number>()); - - // MULTI0-MAPS - _Test_multi_map(new std.HashMultiMap, number>()); - _Test_multi_map(new std.TreeMultiMap, number>()); - _Test_multi_map( - new std.experimental.FlatMultiMap, number>(), - ); + //---- + // SET-CONTAINERS + //---- + // UNIQUE-SETS + _Test_unique_set(new std.HashSet>()); + _Test_unique_set(new std.TreeSet>()); + _Test_unique_set(new std.experimental.FlatSet>()); + + // MULTI-SETS + _Test_multi_set(new std.HashMultiSet>()); + _Test_multi_set(new std.TreeMultiSet>()); + _Test_multi_set(new std.experimental.FlatMultiSet>()); + + //---- + // MAP-CONTAINERS + //---- + // UNIQUE-MAPS + _Test_unique_map(new std.HashMap, number>()); + _Test_unique_map(new std.TreeMap, number>()); + _Test_unique_map(new std.experimental.FlatMap, number>()); + + // MULTI0-MAPS + _Test_multi_map(new std.HashMultiMap, number>()); + _Test_multi_map(new std.TreeMultiMap, number>()); + _Test_multi_map(new std.experimental.FlatMultiMap, number>()); } /* --------------------------------------------------------- SET CONTAINERS --------------------------------------------------------- */ function _Test_unique_set< - Unique extends boolean, - Source extends std.base.SetContainer< - Atomic, - Unique, - Source, - IteratorT, - ReverseT - >, - IteratorT extends std.base.SetContainer.Iterator< - Atomic, - Unique, - Source, - IteratorT, - ReverseT - >, - ReverseT extends std.base.SetContainer.ReverseIterator< - Atomic, - Unique, - Source, - IteratorT, - ReverseT - >, + Unique extends boolean, + Source extends std.base.SetContainer< + Atomic, + Unique, + Source, + IteratorT, + ReverseT + >, + IteratorT extends std.base.SetContainer.Iterator< + Atomic, + Unique, + Source, + IteratorT, + ReverseT + >, + ReverseT extends std.base.SetContainer.ReverseIterator< + Atomic, + Unique, + Source, + IteratorT, + ReverseT + >, >(set: Source): void { - // CONSTRUCT ELEMENTS - _Construct_set(set); - - // DUPLICATED ? - if (set.size() !== 11) - throw new Error( - `Bug on ${set.constructor.name}: wrong number of elements are stored.`, - ); + // CONSTRUCT ELEMENTS + _Construct_set(set); - let sum: number = 0; - for (const elem of set) { - // TO VALIDATE - sum += elem.value; - - // RE-FIND THE ELEMENT BY ITS KEY WITH FIND() FUNCTION. - const it = set.find(elem); - if (it.equals(set.end()) === true) - throw new Error( - `Bug on ${set.constructor.name}.find(): failed to find anything.`, - ); - else if (it.value.equals(elem) === false) - throw new Error( - `Bug on ${set.constructor.name}.find(): found wrong item.`, - ); - } + // DUPLICATED ? + if (set.size() !== 11) + throw new Error( + `Bug on ${set.constructor.name}: wrong number of elements are stored.`, + ); - // RE-VALIDATE UNIQUENESS & RIGHT INSERTION - if (sum !== 55) - throw new Error( - `Bug on ${set.constructor.name}: elements are not fully inserted.`, - ); + let sum: number = 0; + for (const elem of set) { + // TO VALIDATE + sum += elem.value; + + // RE-FIND THE ELEMENT BY ITS KEY WITH FIND() FUNCTION. + const it = set.find(elem); + if (it.equals(set.end()) === true) + throw new Error( + `Bug on ${set.constructor.name}.find(): failed to find anything.`, + ); + else if (it.value.equals(elem) === false) + throw new Error( + `Bug on ${set.constructor.name}.find(): found wrong item.`, + ); + } + + // RE-VALIDATE UNIQUENESS & RIGHT INSERTION + if (sum !== 55) + throw new Error( + `Bug on ${set.constructor.name}: elements are not fully inserted.`, + ); } function _Test_multi_set< - Unique extends boolean, - Source extends std.base.SetContainer< - Atomic, - Unique, - Source, - IteratorT, - ReverseT - >, - IteratorT extends std.base.SetContainer.Iterator< - Atomic, - Unique, - Source, - IteratorT, - ReverseT - >, - ReverseT extends std.base.SetContainer.ReverseIterator< - Atomic, - Unique, - Source, - IteratorT, - ReverseT - >, + Unique extends boolean, + Source extends std.base.SetContainer< + Atomic, + Unique, + Source, + IteratorT, + ReverseT + >, + IteratorT extends std.base.SetContainer.Iterator< + Atomic, + Unique, + Source, + IteratorT, + ReverseT + >, + ReverseT extends std.base.SetContainer.ReverseIterator< + Atomic, + Unique, + Source, + IteratorT, + ReverseT + >, >(set: Source): void { - // CONSTRUCT ELEMENTS - _Construct_set(set); - - // DUPLICATED ? - if (set.size() !== 3 * 11) - throw new Error( - `Bug on ${set.constructor.name}: wrong number of elements are stored.`, - ); - - let sum: number = 0; - for (const elem of set) { - // TO VALIDATE - sum += elem.value; + // CONSTRUCT ELEMENTS + _Construct_set(set); - // RE-FIND THE ELEMENT BY ITS KEY WITH FIND() & COUNT() FUNCTION. - const it = set.find(elem); - const count = set.count(elem); - - if (it.equals(set.end()) === true) - throw new Error( - `Bug on ${set.constructor.name}: failed to find anything.`, - ); - else if (it.value.equals(elem) === false) - throw new Error( - `Bug on ${set.constructor.name}.find(): found wrong item.`, - ); - else if (count !== 3) - throw new Error( - `Bug on ${set.constructor.name}.count(): wrong number of duplicated items.`, - ); - } + // DUPLICATED ? + if (set.size() !== 3 * 11) + throw new Error( + `Bug on ${set.constructor.name}: wrong number of elements are stored.`, + ); - // RE-VALIDATE DUPLICATION & RIGHT INSERTION - if (sum !== 3 * 55) - throw new Error( - `Bug on ${set.constructor.name}: elements are not fully inserted.`, - ); + let sum: number = 0; + for (const elem of set) { + // TO VALIDATE + sum += elem.value; + + // RE-FIND THE ELEMENT BY ITS KEY WITH FIND() & COUNT() FUNCTION. + const it = set.find(elem); + const count = set.count(elem); + + if (it.equals(set.end()) === true) + throw new Error( + `Bug on ${set.constructor.name}: failed to find anything.`, + ); + else if (it.value.equals(elem) === false) + throw new Error( + `Bug on ${set.constructor.name}.find(): found wrong item.`, + ); + else if (count !== 3) + throw new Error( + `Bug on ${set.constructor.name}.count(): wrong number of duplicated items.`, + ); + } + + // RE-VALIDATE DUPLICATION & RIGHT INSERTION + if (sum !== 3 * 55) + throw new Error( + `Bug on ${set.constructor.name}: elements are not fully inserted.`, + ); } function _Construct_set< - Unique extends boolean, - Source extends std.base.SetContainer< - Atomic, - Unique, - Source, - IteratorT, - ReverseT - >, - IteratorT extends std.base.SetContainer.Iterator< - Atomic, - Unique, - Source, - IteratorT, - ReverseT - >, - ReverseT extends std.base.SetContainer.ReverseIterator< - Atomic, - Unique, - Source, - IteratorT, - ReverseT - >, + Unique extends boolean, + Source extends std.base.SetContainer< + Atomic, + Unique, + Source, + IteratorT, + ReverseT + >, + IteratorT extends std.base.SetContainer.Iterator< + Atomic, + Unique, + Source, + IteratorT, + ReverseT + >, + ReverseT extends std.base.SetContainer.ReverseIterator< + Atomic, + Unique, + Source, + IteratorT, + ReverseT + >, >(set: Source): void { - // INSERT ELEMENTS - for (let i: number = 0; i <= 10; ++i) - for (let j: number = 0; j < 3; ++j) set.push(new Atomic(i)); - - // TEST SEQUENCE - const vec = new std.Vector>(set.begin(), set.end()); - if (std.is_sorted(vec.begin(), vec.end()) === false) - throw new Error( - `Bug on ${set.constructor.name}: stored elements are not sorted.`, - ); + // INSERT ELEMENTS + for (let i: number = 0; i <= 10; ++i) + for (let j: number = 0; j < 3; ++j) set.push(new Atomic(i)); + + // TEST SEQUENCE + const vec = new std.Vector>(set.begin(), set.end()); + if (std.is_sorted(vec.begin(), vec.end()) === false) + throw new Error( + `Bug on ${set.constructor.name}: stored elements are not sorted.`, + ); } /* --------------------------------------------------------- MAP CONTAINERS --------------------------------------------------------- */ function _Test_unique_map< - Source extends std.base.UniqueMap< - Atomic, - number, - Source, - IteratorT, - ReverseT - >, - IteratorT extends std.base.MapContainer.Iterator< - Atomic, - number, - true, - Source, - IteratorT, - ReverseT - >, - ReverseT extends std.base.MapContainer.ReverseIterator< - Atomic, - number, - true, - Source, - IteratorT, - ReverseT - >, + Source extends std.base.UniqueMap< + Atomic, + number, + Source, + IteratorT, + ReverseT + >, + IteratorT extends std.base.MapContainer.Iterator< + Atomic, + number, + true, + Source, + IteratorT, + ReverseT + >, + ReverseT extends std.base.MapContainer.ReverseIterator< + Atomic, + number, + true, + Source, + IteratorT, + ReverseT + >, >(map: Source): void { - // CONSTRUCT ELEMENTS - _Construct_map(map); - - // DUPLICATED ? - if (map.size() !== 11) - throw new Error( - `Bug on ${map.constructor.name}: wrong number of elements are stored.`, - ); + // CONSTRUCT ELEMENTS + _Construct_map(map); - let sum: number = 0; - for (const pair of map) { - // TO VALIDATE - sum += pair.second; - - // RE-FIND THE ELEMENT BY ITS KEY WITH FIND() FUNCTION. - const it = map.find(pair.first); - if (it.equals(map.end()) === true) - throw new Error( - `Bug on ${map.constructor.name}.find(): failed to find anything.`, - ); - else if (it.first.equals(pair.first) === false) - throw new Error( - `Bug on ${map.constructor.name}.find(): found wrong item.`, - ); - } + // DUPLICATED ? + if (map.size() !== 11) + throw new Error( + `Bug on ${map.constructor.name}: wrong number of elements are stored.`, + ); - // RE-VALIDATE UNIQUENESS & RIGHT INSERTION - if (sum !== 55) - throw new Error( - `Bug on ${map.constructor.name}: elements are not fully inserted.`, - ); + let sum: number = 0; + for (const pair of map) { + // TO VALIDATE + sum += pair.second; + + // RE-FIND THE ELEMENT BY ITS KEY WITH FIND() FUNCTION. + const it = map.find(pair.first); + if (it.equals(map.end()) === true) + throw new Error( + `Bug on ${map.constructor.name}.find(): failed to find anything.`, + ); + else if (it.first.equals(pair.first) === false) + throw new Error( + `Bug on ${map.constructor.name}.find(): found wrong item.`, + ); + } + + // RE-VALIDATE UNIQUENESS & RIGHT INSERTION + if (sum !== 55) + throw new Error( + `Bug on ${map.constructor.name}: elements are not fully inserted.`, + ); } function _Test_multi_map< - Source extends std.base.MultiMap< - Atomic, - number, - Source, - IteratorT, - ReverseT - >, - IteratorT extends std.base.MapContainer.Iterator< - Atomic, - number, - false, - Source, - IteratorT, - ReverseT - >, - ReverseT extends std.base.MapContainer.ReverseIterator< - Atomic, - number, - false, - Source, - IteratorT, - ReverseT - >, + Source extends std.base.MultiMap< + Atomic, + number, + Source, + IteratorT, + ReverseT + >, + IteratorT extends std.base.MapContainer.Iterator< + Atomic, + number, + false, + Source, + IteratorT, + ReverseT + >, + ReverseT extends std.base.MapContainer.ReverseIterator< + Atomic, + number, + false, + Source, + IteratorT, + ReverseT + >, >(map: Source): void { - // CONSTRUCT ELEMENTS - _Construct_map(map); + // CONSTRUCT ELEMENTS + _Construct_map(map); - // DUPLICATED ? - if (map.size() !== 3 * 11) - throw new Error( - `Bug on ${map.constructor.name}: wrong number of elements are stored.`, - ); - - let sum: number = 0; - for (const pair of map) { - // TO VALIDATE - sum += pair.second; - - // RE-FIND THE ELEMENT BY ITS KEY WITH FIND() & COUNT() FUNCTION. - const it = map.find(pair.first); - const count = map.count(pair.first); - - if (it.equals(map.end()) === true) - throw new Error( - `Bug on ${map.constructor.name}.find(): failed to find anything.`, - ); - else if (it.first.equals(pair.first) === false) - throw new Error( - `Bug on ${map.constructor.name}.find(): found wrong item.`, - ); - else if (count !== 3) - throw new Error( - `Bug on ${map.constructor.name}.count(): wrong number of duplicated items.`, - ); - } + // DUPLICATED ? + if (map.size() !== 3 * 11) + throw new Error( + `Bug on ${map.constructor.name}: wrong number of elements are stored.`, + ); - // RE-VALIDATE UNIQUENESS & RIGHT INSERTION - if (sum !== 3 * 55) - throw new Error( - `Bug on ${map.constructor.name}: elements are not fully inserted.`, - ); + let sum: number = 0; + for (const pair of map) { + // TO VALIDATE + sum += pair.second; + + // RE-FIND THE ELEMENT BY ITS KEY WITH FIND() & COUNT() FUNCTION. + const it = map.find(pair.first); + const count = map.count(pair.first); + + if (it.equals(map.end()) === true) + throw new Error( + `Bug on ${map.constructor.name}.find(): failed to find anything.`, + ); + else if (it.first.equals(pair.first) === false) + throw new Error( + `Bug on ${map.constructor.name}.find(): found wrong item.`, + ); + else if (count !== 3) + throw new Error( + `Bug on ${map.constructor.name}.count(): wrong number of duplicated items.`, + ); + } + + // RE-VALIDATE UNIQUENESS & RIGHT INSERTION + if (sum !== 3 * 55) + throw new Error( + `Bug on ${map.constructor.name}: elements are not fully inserted.`, + ); } function _Construct_map< - Unique extends boolean, - Source extends std.base.MapContainer< - Atomic, - number, - Unique, - Source, - IteratorT, - ReverseT - >, - IteratorT extends std.base.MapContainer.Iterator< - Atomic, - number, - Unique, - Source, - IteratorT, - ReverseT - >, - ReverseT extends std.base.MapContainer.ReverseIterator< - Atomic, - number, - Unique, - Source, - IteratorT, - ReverseT - >, + Unique extends boolean, + Source extends std.base.MapContainer< + Atomic, + number, + Unique, + Source, + IteratorT, + ReverseT + >, + IteratorT extends std.base.MapContainer.Iterator< + Atomic, + number, + Unique, + Source, + IteratorT, + ReverseT + >, + ReverseT extends std.base.MapContainer.ReverseIterator< + Atomic, + number, + Unique, + Source, + IteratorT, + ReverseT + >, >(map: Source): void { - for (let i: number = 0; i <= 10; ++i) - for (let j: number = 0; j < 3; ++j) { - const key: Atomic = new Atomic(NUMBER_NAMES[i]); - const value: number = i; + for (let i: number = 0; i <= 10; ++i) + for (let j: number = 0; j < 3; ++j) { + const key: Atomic = new Atomic(NUMBER_NAMES[i]); + const value: number = i; - map.push(std.make_pair(key, value)); - } + map.push(std.make_pair(key, value)); + } } const NUMBER_NAMES: string[] = [ - "Zero", - "First", - "Second", - "Third", - "Fourth", - "Fifth", - "Sixth", - "Seventh", - "Eighth", - "Nineth", - "Tenth", + "Zero", + "First", + "Second", + "Third", + "Fourth", + "Fifth", + "Sixth", + "Seventh", + "Eighth", + "Nineth", + "Tenth", ]; diff --git a/src/test/container/test_for_of_iterations.ts b/src/test/container/test_for_of_iterations.ts index 38d10f60..4fdfa9a3 100644 --- a/src/test/container/test_for_of_iterations.ts +++ b/src/test/container/test_for_of_iterations.ts @@ -1,72 +1,70 @@ import * as std from "../../index"; export function test_for_of_iterations(): void { - // LINEAR CONTAINERS - _Test_for_of_iteration(new std.Vector()); - _Test_for_of_iteration(new std.Deque()); - _Test_for_of_iteration(new std.List()); + // LINEAR CONTAINERS + _Test_for_of_iteration(new std.Vector()); + _Test_for_of_iteration(new std.Deque()); + _Test_for_of_iteration(new std.List()); - // ASSOCIATIVE CONTAINERS - _Test_for_of_iteration(new std.TreeSet()); - _Test_for_of_map_iteration(); + // ASSOCIATIVE CONTAINERS + _Test_for_of_iteration(new std.TreeSet()); + _Test_for_of_map_iteration(); } function _Test_for_of_iteration< - SourceT extends std.base.IContainer, - IteratorT extends std.base.IContainer.Iterator< - number, - SourceT, - IteratorT, - ReverseT - >, - ReverseT extends std.base.IContainer.ReverseIterator< - number, - SourceT, - IteratorT, - ReverseT - >, + SourceT extends std.base.IContainer, + IteratorT extends std.base.IContainer.Iterator< + number, + SourceT, + IteratorT, + ReverseT + >, + ReverseT extends std.base.IContainer.ReverseIterator< + number, + SourceT, + IteratorT, + ReverseT + >, >(vec: SourceT): void { - //---- - // CONSTRUCTIONS - //---- - // CONSTRUCT ITEMS TO VALIDATE - const items: std.Vector = new std.Vector(10, 0); - std.iota(std.begin(items), std.end(items), 0); + //---- + // CONSTRUCTIONS + //---- + // CONSTRUCT ITEMS TO VALIDATE + const items: std.Vector = new std.Vector(10, 0); + std.iota(std.begin(items), std.end(items), 0); - // PUSH THEM ALL TO THE CONTAINER - vec.assign(std.begin(items), std.end(items)); + // PUSH THEM ALL TO THE CONTAINER + vec.assign(std.begin(items), std.end(items)); - //---- - // VALIDATION - //---- - let i: number = 0; + //---- + // VALIDATION + //---- + let i: number = 0; - for (const elem of vec) - if (elem !== items.at(i++)) - throw new Error( - `Bug on ${vec.constructor.name}[Symbol.iterator]().`, - ); + for (const elem of vec) + if (elem !== items.at(i++)) + throw new Error(`Bug on ${vec.constructor.name}[Symbol.iterator]().`); } function _Test_for_of_map_iteration(): void { - //---- - // CONSTRUCTIONS - //---- - // CONSTRUCT ITEMS TO VALIDATE - const map = new std.TreeMap(); - const items: std.Pair[] = []; + //---- + // CONSTRUCTIONS + //---- + // CONSTRUCT ITEMS TO VALIDATE + const map = new std.TreeMap(); + const items: std.Pair[] = []; - for (let i: number = 0; i < 10; ++i) items.push(std.make_pair(i, i)); + for (let i: number = 0; i < 10; ++i) items.push(std.make_pair(i, i)); - // PUSH THEM ALL TO THE CONTAINER - map.push(...items); + // PUSH THEM ALL TO THE CONTAINER + map.push(...items); - //---- - // VALIDATION - //---- - let i: number = 0; + //---- + // VALIDATION + //---- + let i: number = 0; - for (const pair of map) - if (std.equal_to(pair, items[i++]) === false) - throw new Error("Bug on TreeMap[Symbol.iterator]()."); + for (const pair of map) + if (std.equal_to(pair, items[i++]) === false) + throw new Error("Bug on TreeMap[Symbol.iterator]()."); } diff --git a/src/test/container/test_hash_maps.ts b/src/test/container/test_hash_maps.ts index 2bbd8378..12df1fb6 100644 --- a/src/test/container/test_hash_maps.ts +++ b/src/test/container/test_hash_maps.ts @@ -3,39 +3,39 @@ import * as std from "../../index"; const CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; function random_characters(length: number): string { - let ret: string = ""; - for (let i: number = 0; i < length; ++i) { - const index: number = std.randint(9, CHARACTERS.length - 1); - ret += CHARACTERS[index]; - } - return ret; + let ret: string = ""; + for (let i: number = 0; i < length; ++i) { + const index: number = std.randint(9, CHARACTERS.length - 1); + ret += CHARACTERS[index]; + } + return ret; } export function test_hash_maps(): void { - type Key = std.Pair, std.Pair>; - const Key = std.Pair; - - const dict: std.HashMap = new std.HashMap(); - const tuples: Array<[Key, number]> = []; - - for (let i: number = 0; i < 100; ++i) { - const key: Key = new Key( - new std.Pair(new Object(), random_characters(3)), - new std.Pair(new Object(), random_characters(7)), - ); - const value: number = std.randint(0, 5000); - - dict.emplace(key, value); - tuples.push([key, value]); - } - std.ranges.shuffle(tuples); - - for (const t of tuples) { - const key: Key = t[0]; - const value: number = t[1]; - - const it: std.HashMap.Iterator = dict.find(key); - if (it.first !== key || it.second !== value) - throw new Error("Error on hash algorithm, maybe."); - } + type Key = std.Pair, std.Pair>; + const Key = std.Pair; + + const dict: std.HashMap = new std.HashMap(); + const tuples: Array<[Key, number]> = []; + + for (let i: number = 0; i < 100; ++i) { + const key: Key = new Key( + new std.Pair(new Object(), random_characters(3)), + new std.Pair(new Object(), random_characters(7)), + ); + const value: number = std.randint(0, 5000); + + dict.emplace(key, value); + tuples.push([key, value]); + } + std.ranges.shuffle(tuples); + + for (const t of tuples) { + const key: Key = t[0]; + const value: number = t[1]; + + const it: std.HashMap.Iterator = dict.find(key); + if (it.first !== key || it.second !== value) + throw new Error("Error on hash algorithm, maybe."); + } } diff --git a/src/test/container/test_linears.ts b/src/test/container/test_linears.ts index ce9bfab4..a68ec408 100644 --- a/src/test/container/test_linears.ts +++ b/src/test/container/test_linears.ts @@ -2,108 +2,108 @@ import * as std from "../../index"; import { Temporary } from "../../internal/functional/Temporary"; export function test_linear_containers(): void { - _Test_linear(new std.Vector()); - _Test_linear(new std.Deque()); - _Test_linear(new std.List()); + _Test_linear(new std.Vector()); + _Test_linear(new std.Deque()); + _Test_linear(new std.List()); } function _Test_linear< - SourceT extends std.base.ILinearContainer< - number, - SourceT, - IteratorT, - ReverseT - >, - IteratorT extends std.base.IContainer.Iterator< - number, - SourceT, - IteratorT, - ReverseT - >, - ReverseT extends std.base.IContainer.ReverseIterator< - number, - SourceT, - IteratorT, - ReverseT - >, + SourceT extends std.base.ILinearContainer< + number, + SourceT, + IteratorT, + ReverseT + >, + IteratorT extends std.base.IContainer.Iterator< + number, + SourceT, + IteratorT, + ReverseT + >, + ReverseT extends std.base.IContainer.ReverseIterator< + number, + SourceT, + IteratorT, + ReverseT + >, >(vec: SourceT): void { - //---- - // CONSTRUCT ELEMENTS - //---- - // 0 ~ 9 - vec.assign(10, 0); - std.iota(vec.begin(), vec.end(), 0); + //---- + // CONSTRUCT ELEMENTS + //---- + // 0 ~ 9 + vec.assign(10, 0); + std.iota(vec.begin(), vec.end(), 0); - //---- - // ELEMENTS I/O - //---- - // ERASE AN ELEMENT - let it: IteratorT = std.advance(vec.begin(), 3); // STEP TO 3 - it = vec.erase(it); // AND ERASE THE 3 + //---- + // ELEMENTS I/O + //---- + // ERASE AN ELEMENT + let it: IteratorT = std.advance(vec.begin(), 3); // STEP TO 3 + it = vec.erase(it); // AND ERASE THE 3 - if (it.value !== 4) - // MUST BE 4 - throw new Error( - `Bug on ${vec.constructor.name}: nth(3) must be 4, but ${it.value}`, - ); + if (it.value !== 4) + // MUST BE 4 + throw new Error( + `Bug on ${vec.constructor.name}: nth(3) must be 4, but ${it.value}`, + ); - // INSERT AN ELEMENT - it = std.advance(vec.begin(), 2); - it = vec.insert(it, -1); // insert -1 + // INSERT AN ELEMENT + it = std.advance(vec.begin(), 2); + it = vec.insert(it, -1); // insert -1 - if (it.value !== -1) - throw new Error( - `Bug on ${vec.constructor.name}.inser(): returned iterator is not exact, it must be -1 but ${it.value}`, - ); + if (it.value !== -1) + throw new Error( + `Bug on ${vec.constructor.name}.inser(): returned iterator is not exact, it must be -1 but ${it.value}`, + ); - // ERASE RANGE - it = std.advance(vec.begin(), 6); - it = vec.erase(it, std.advance(it, 3)); // erase from 6 to 9 + // ERASE RANGE + it = std.advance(vec.begin(), 6); + it = vec.erase(it, std.advance(it, 3)); // erase from 6 to 9 - if (it.value !== 9) - throw Error( - `Bug on ${vec.constructor.name}.erase(): returned iterator is not exact, it must be 9 but ${it.value}`, - ); + if (it.value !== 9) + throw Error( + `Bug on ${vec.constructor.name}.erase(): returned iterator is not exact, it must be 9 but ${it.value}`, + ); - //---- - // FINAL VALIDATION - //---- - _Validate_linear_elements(vec, [0, 1, -1, 2, 4, 5, 9]); + //---- + // FINAL VALIDATION + //---- + _Validate_linear_elements(vec, [0, 1, -1, 2, 4, 5, 9]); } function _Validate_linear_elements< - SourceT extends std.base.ILinearContainer< - number, - SourceT, - IteratorT, - ReverseT - >, - IteratorT extends std.base.IContainer.Iterator< - number, - SourceT, - IteratorT, - ReverseT - >, - ReverseT extends std.base.IContainer.ReverseIterator< - number, - SourceT, - IteratorT, - ReverseT - >, + SourceT extends std.base.ILinearContainer< + number, + SourceT, + IteratorT, + ReverseT + >, + IteratorT extends std.base.IContainer.Iterator< + number, + SourceT, + IteratorT, + ReverseT + >, + ReverseT extends std.base.IContainer.ReverseIterator< + number, + SourceT, + IteratorT, + ReverseT + >, >(vec: SourceT, answer: number[]): void { - if (vec.size() !== answer.length) - throw new Error( - `Bug on ${ - vec.constructor.name - }: number of stored elements are wrong, it must be ${ - answer.length - } but ${vec.size()}`, - ); + if (vec.size() !== answer.length) + throw new Error( + `Bug on ${ + vec.constructor.name + }: number of stored elements are wrong, it must be ${ + answer.length + } but ${vec.size()}`, + ); - let i: number = 0; - for (let it = vec.begin(); !it.equals(vec.end()); it = it.next()) - if (it.value !== answer[i++]) - throw new Error( - `Bug on ${vec.constructor.name}: number of stored elements are different: it must be ${answer[i]} but ${it.value}`, - ); + let i: number = 0; + for (let it = vec.begin(); !it.equals(vec.end()); it = it.next()) + if (it.value !== answer[i++]) + throw new Error( + `Bug on ${vec.constructor.name}: number of stored elements are different: it must be ${answer[i]} but ${it.value}`, + ); } diff --git a/src/test/container/test_lists.ts b/src/test/container/test_lists.ts index 816efad6..c96203f2 100644 --- a/src/test/container/test_lists.ts +++ b/src/test/container/test_lists.ts @@ -1,116 +1,112 @@ import * as std from "../../index"; export function test_lists(): void { - _Test_removes(); - _Test_merges(); + _Test_removes(); + _Test_merges(); - _Test_forward_lists(); + _Test_forward_lists(); } function _Test_removes(): void { - const v = new std.Vector(); - for (let i: number = 0; i < 10; ++i) v.push_back(Math.random()); + const v = new std.Vector(); + for (let i: number = 0; i < 10; ++i) v.push_back(Math.random()); - _Test_remove(std.List, v); - _Test_remove(std.ForwardList as any, v); + _Test_remove(std.List, v); + _Test_remove(std.ForwardList as any, v); } function _Test_remove(creator: typeof std.List, v: std.Vector): void { - const l = new creator(v.begin(), v.end()); - l.remove_if(_Remove_if); - l.reverse(); + const l = new creator(v.begin(), v.end()); + l.remove_if(_Remove_if); + l.reverse(); - v.erase(std.remove_if(v.begin(), v.end(), _Remove_if), v.end()); - if (std.equal(l.begin(), l.end(), v.rbegin()) === false) - throw new Error(`Bug on ${creator.name}.remove_if()`); + v.erase(std.remove_if(v.begin(), v.end(), _Remove_if), v.end()); + if (std.equal(l.begin(), l.end(), v.rbegin()) === false) + throw new Error(`Bug on ${creator.name}.remove_if()`); } function _Remove_if(val: number): boolean { - return val < 0.5; + return val < 0.5; } function _Test_merges(): void { - //---- - // PRELIMINARIES - //---- - // SAMPLE DATA - const v1 = new std.Vector([1, 2, 3, 7, 8, 15, 16]); - const v2 = new std.Vector([5, 6, 12, 13]); - - // ARE SHUFFLED - std.shuffle(v1.begin(), v1.end()); - std.shuffle(v2.begin(), v2.end()); - - // VALIDATOR; SORTED & MERGED BY TREE-SET - const set = new std.TreeSet(v1.data()); - set.push(...v2.data()); - - //---- - // VALIDATE - //---- - _Test_merge(std.List, v1, v2, set); - _Test_merge(std.ForwardList as any, v1, v2, set); + //---- + // PRELIMINARIES + //---- + // SAMPLE DATA + const v1 = new std.Vector([1, 2, 3, 7, 8, 15, 16]); + const v2 = new std.Vector([5, 6, 12, 13]); + + // ARE SHUFFLED + std.shuffle(v1.begin(), v1.end()); + std.shuffle(v2.begin(), v2.end()); + + // VALIDATOR; SORTED & MERGED BY TREE-SET + const set = new std.TreeSet(v1.data()); + set.push(...v2.data()); + + //---- + // VALIDATE + //---- + _Test_merge(std.List, v1, v2, set); + _Test_merge(std.ForwardList as any, v1, v2, set); } function _Test_merge( - creator: typeof std.List, - v1: std.Vector, - v2: std.Vector, - set: std.TreeSet, + creator: typeof std.List, + v1: std.Vector, + v2: std.Vector, + set: std.TreeSet, ): void { - // CONSTRUCT LISTS - const l1 = new creator(v1.data()); - const l2 = new creator(v2.data()); + // CONSTRUCT LISTS + const l1 = new creator(v1.data()); + const l2 = new creator(v2.data()); - // SORT THEM TO MERGE - l1.sort(); - l2.sort(); + // SORT THEM TO MERGE + l1.sort(); + l2.sort(); - // DO MERGE - l1.merge(l2); + // DO MERGE + l1.merge(l2); - // VALIDATE - if ((std.equal as Function)(l1.begin(), l1.end(), set.begin()) === false) - throw new Error(`Bug on ${creator.name}.merge().`); + // VALIDATE + if ((std.equal as Function)(l1.begin(), l1.end(), set.begin()) === false) + throw new Error(`Bug on ${creator.name}.merge().`); } function _Test_forward_lists(): void { - //---- - // CONSTRUCT ELEMENTS - //---- - const fl: std.ForwardList = new std.ForwardList(); - for (let i: number = 9; i >= 0; --i) fl.push_front(i); - - //---- - // ELEMENTS I/O - //---- - let it = std.advance(fl.before_begin(), 3); // STEP TO 2 - it = fl.erase_after(it); // AND ERASE 3 BY ERASE_AFTER() - - if (it.value !== 4) - throw new Error( - "Bug on std.ForwardList.erase_after(); single deletion.", - ); - - // INSERT AN ELEMENT - it = std.advance(fl.before_begin(), 2); - it = fl.insert_after(it, -1); // INSERT -1 - - if (it.value !== -1) - throw new Error("Bug on std.ForwardList.insert_after()."); - - // ERASE RANGE - it = std.advance(fl.before_begin(), 6); - it = fl.erase_after(it, std.advance(it, 3 + 1)); - - if (it.value !== 9) - throw new Error( - "Bug on std.ForwardList.erase_after(); range deletion.", - ); - - //---- - // FINAL VALIDATION - //---- - const answer = new std.Vector([0, 1, -1, 2, 4, 5, 9]); - if (std.equal(fl.begin(), fl.end(), answer.begin()) === false) - throw new Error("Bug on std.ForwardList; store elements are wrong."); + //---- + // CONSTRUCT ELEMENTS + //---- + const fl: std.ForwardList = new std.ForwardList(); + for (let i: number = 9; i >= 0; --i) fl.push_front(i); + + //---- + // ELEMENTS I/O + //---- + let it = std.advance(fl.before_begin(), 3); // STEP TO 2 + it = fl.erase_after(it); // AND ERASE 3 BY ERASE_AFTER() + + if (it.value !== 4) + throw new Error("Bug on std.ForwardList.erase_after(); single deletion."); + + // INSERT AN ELEMENT + it = std.advance(fl.before_begin(), 2); + it = fl.insert_after(it, -1); // INSERT -1 + + if (it.value !== -1) + throw new Error("Bug on std.ForwardList.insert_after()."); + + // ERASE RANGE + it = std.advance(fl.before_begin(), 6); + it = fl.erase_after(it, std.advance(it, 3 + 1)); + + if (it.value !== 9) + throw new Error("Bug on std.ForwardList.erase_after(); range deletion."); + + //---- + // FINAL VALIDATION + //---- + const answer = new std.Vector([0, 1, -1, 2, 4, 5, 9]); + if (std.equal(fl.begin(), fl.end(), answer.begin()) === false) + throw new Error("Bug on std.ForwardList; store elements are wrong."); } diff --git a/src/test/container/test_swaps.ts b/src/test/container/test_swaps.ts index fbcff7af..8d04d4e3 100644 --- a/src/test/container/test_swaps.ts +++ b/src/test/container/test_swaps.ts @@ -3,205 +3,192 @@ import * as std from "../../index"; type P = std.Pair; export function test_swaps(): void { - //---- - // REGULAR CONTAINERS - //---- - // LINEARS - _Test_container_swap(new std.Vector

(), new std.Vector

()); - _Test_container_swap(new std.Deque

(), new std.Deque

()); - _Test_container_swap(new std.List

(), new std.List

()); - - // SET CONTAINERS - _Test_container_swap(new std.TreeSet

(), new std.TreeSet

()); - _Test_container_swap(new std.TreeMultiSet

(), new std.TreeMultiSet

()); - _Test_container_swap(new std.HashSet

(), new std.HashSet

()); - _Test_container_swap(new std.HashMultiSet

(), new std.HashMultiSet

()); - - // MAP CONTAINERS - _Test_container_swap( - new std.TreeMap(), - new std.TreeMap(), - ); - _Test_container_swap( - new std.TreeMultiMap(), - new std.TreeMultiMap(), - ); - _Test_container_swap( - new std.HashMap(), - new std.HashMap(), - ); - _Test_container_swap( - new std.HashMultiMap(), - new std.HashMultiMap(), - ); - - //---- - // SPECIAL CONTAINERS - //---- - _Test_vector_bool_swap(); - _Test_forward_list_swap(); + //---- + // REGULAR CONTAINERS + //---- + // LINEARS + _Test_container_swap(new std.Vector

(), new std.Vector

()); + _Test_container_swap(new std.Deque

(), new std.Deque

()); + _Test_container_swap(new std.List

(), new std.List

()); + + // SET CONTAINERS + _Test_container_swap(new std.TreeSet

(), new std.TreeSet

()); + _Test_container_swap(new std.TreeMultiSet

(), new std.TreeMultiSet

()); + _Test_container_swap(new std.HashSet

(), new std.HashSet

()); + _Test_container_swap(new std.HashMultiSet

(), new std.HashMultiSet

()); + + // MAP CONTAINERS + _Test_container_swap( + new std.TreeMap(), + new std.TreeMap(), + ); + _Test_container_swap( + new std.TreeMultiMap(), + new std.TreeMultiMap(), + ); + _Test_container_swap( + new std.HashMap(), + new std.HashMap(), + ); + _Test_container_swap( + new std.HashMultiMap(), + new std.HashMultiMap(), + ); + + //---- + // SPECIAL CONTAINERS + //---- + _Test_vector_bool_swap(); + _Test_forward_list_swap(); } /* --------------------------------------------------------- REGULAR CONTAINERS --------------------------------------------------------- */ function _Test_container_swap< - SourceT extends std.base.IContainer, - IteratorT extends std.base.IContainer.Iterator< - P, - SourceT, - IteratorT, - ReverseT - >, - ReverseT extends std.base.IContainer.ReverseIterator< - P, - SourceT, - IteratorT, - ReverseT - >, + SourceT extends std.base.IContainer, + IteratorT extends std.base.IContainer.Iterator< + P, + SourceT, + IteratorT, + ReverseT + >, + ReverseT extends std.base.IContainer.ReverseIterator< + P, + SourceT, + IteratorT, + ReverseT + >, >(v1: SourceT, v2: SourceT): void { - // INSERT ITEMS ON EACH CONTAINERS - for (let i: number = 1; i <= 3; ++i) { - v1.push(std.make_pair(i, i)); - v2.push(std.make_pair(i + 3, i + 3)); - } - - // SWAP THEM - v1.swap(v2); - - // VALIDATE CONTENTS - let sum: number = 0; - for (const pair of v1) sum += pair.first; - - if (sum !== 4 + 5 + 6) - throw new Error(`Bug on ${v1.constructor.name}.swap(); contents.`); - else if (v1.begin().source() !== v1) - throw new Error(`Bug on ${v1.constructor.name}.swap(); source.`); - - // VALIDATE NEW ITEMS - v1.push(std.make_pair(7, 7)); - if (v1.end().prev().source() !== v1) - throw new Error( - `Bug on ${v1.constructor.name}.swap(); source of newly inserted item.`, - ); - - // VALIDATE ITERATORS' SOURCE - _Validate_iterators_source(v1); - _Validate_iterators_source(v2); - - // SPECIAL VALIDATION -> SET OR MAP + // INSERT ITEMS ON EACH CONTAINERS + for (let i: number = 1; i <= 3; ++i) { + v1.push(std.make_pair(i, i)); + v2.push(std.make_pair(i + 3, i + 3)); + } + + // SWAP THEM + v1.swap(v2); + + // VALIDATE CONTENTS + let sum: number = 0; + for (const pair of v1) sum += pair.first; + + if (sum !== 4 + 5 + 6) + throw new Error(`Bug on ${v1.constructor.name}.swap(); contents.`); + else if (v1.begin().source() !== v1) + throw new Error(`Bug on ${v1.constructor.name}.swap(); source.`); + + // VALIDATE NEW ITEMS + v1.push(std.make_pair(7, 7)); + if (v1.end().prev().source() !== v1) + throw new Error( + `Bug on ${v1.constructor.name}.swap(); source of newly inserted item.`, + ); + + // VALIDATE ITERATORS' SOURCE + _Validate_iterators_source(v1); + _Validate_iterators_source(v2); + + // SPECIAL VALIDATION -> SET OR MAP + if ( + v1 instanceof std.base.SetContainer && + v2 instanceof std.base.SetContainer + ) { if ( - v1 instanceof std.base.SetContainer && - v2 instanceof std.base.SetContainer - ) { - if ( - v1.find(std.make_pair(5, 5)).source() !== v1 || - v2.find(std.make_pair(2, 2)).source() !== v2 - ) - throw new Error( - `Bug on ${v1.constructor.name}.swap(); Invalid key-source mapping.`, - ); - } else if ( - v1 instanceof std.base.MapContainer && - v2 instanceof std.base.MapContainer - ) { - if (v1.find(4).source() !== v1 || v2.find(1).source() !== v2) - throw new Error( - `Bug on ${v1.constructor.name}.swap(); Invalid key-source mapping.`, - ); - } + v1.find(std.make_pair(5, 5)).source() !== v1 || + v2.find(std.make_pair(2, 2)).source() !== v2 + ) + throw new Error( + `Bug on ${v1.constructor.name}.swap(); Invalid key-source mapping.`, + ); + } else if ( + v1 instanceof std.base.MapContainer && + v2 instanceof std.base.MapContainer + ) { + if (v1.find(4).source() !== v1 || v2.find(1).source() !== v2) + throw new Error( + `Bug on ${v1.constructor.name}.swap(); Invalid key-source mapping.`, + ); + } } function _Validate_iterators_source< + T, + SourceT extends std.base.IContainer, + IteratorT extends std.base.IContainer.Iterator< T, - SourceT extends std.base.IContainer, - IteratorT extends std.base.IContainer.Iterator< - T, - SourceT, - IteratorT, - ReverseT - >, - ReverseT extends std.base.IContainer.ReverseIterator< - T, - SourceT, - IteratorT, - ReverseT - >, + SourceT, + IteratorT, + ReverseT + >, + ReverseT extends std.base.IContainer.ReverseIterator< + T, + SourceT, + IteratorT, + ReverseT + >, >(container: SourceT): void { - for ( - let it = container.begin(); - !it.equals(container.end()); - it = it.next() - ) - if (it.source() !== container) - throw new std.DomainError( - `Bug on ${container.constructor.name}.swap(); reversable-iterator's source.`, - ); - - for ( - let it = container.rbegin(); - !it.equals(container.rend()); - it = it.next() - ) - if (it.source() !== container) - throw new std.DomainError( - `Bug on ${container.constructor.name}.swap(); reverse-iterator's source.`, - ); + for (let it = container.begin(); !it.equals(container.end()); it = it.next()) + if (it.source() !== container) + throw new std.DomainError( + `Bug on ${container.constructor.name}.swap(); reversable-iterator's source.`, + ); + + for ( + let it = container.rbegin(); + !it.equals(container.rend()); + it = it.next() + ) + if (it.source() !== container) + throw new std.DomainError( + `Bug on ${container.constructor.name}.swap(); reverse-iterator's source.`, + ); } /* --------------------------------------------------------- SPECIAL CONTAINERS --------------------------------------------------------- */ function _Test_vector_bool_swap(): void { - const refer: std.VectorBoolean = new std.VectorBoolean(); - for (let i: number = 0; i < 100; ++i) - refer.push_back(Math.random() < 0.5 ? false : true); + const refer: std.VectorBoolean = new std.VectorBoolean(); + for (let i: number = 0; i < 100; ++i) + refer.push_back(Math.random() < 0.5 ? false : true); - const x: std.VectorBoolean = new std.VectorBoolean(refer); - const y: std.VectorBoolean = new std.VectorBoolean(refer); - y.flip(); // {y} = {!x} + const x: std.VectorBoolean = new std.VectorBoolean(refer); + const y: std.VectorBoolean = new std.VectorBoolean(refer); + y.flip(); // {y} = {!x} - x.swap(y); - if (std.equal(refer.begin(), refer.end(), y.begin()) === false) - throw new Error(`Bug on ${x.constructor.name}.swap(); contents.`); + x.swap(y); + if (std.equal(refer.begin(), refer.end(), y.begin()) === false) + throw new Error(`Bug on ${x.constructor.name}.swap(); contents.`); - _Validate_iterators_source(x); - _Validate_iterators_source(y); + _Validate_iterators_source(x); + _Validate_iterators_source(y); } function _Test_forward_list_swap(): void { - const x: std.ForwardList = new std.ForwardList(); - const y: std.ForwardList = new std.ForwardList(); - - for (let i: number = 1; i <= 3; ++i) { - x.push_front(i); - y.push_front(i + 3); - } - x.swap(y); - - let sum: number = 0; - for (let it = x.begin(); !it.equals(x.end()); it = it.next()) - sum += it.value; - - if (sum !== 4 + 5 + 6) - throw new Error( - `Bug on ${x.constructor.name}.swap(); contents -> ${sum}`, - ); - - _Validate_forward_list_iterator_source(x); - _Validate_forward_list_iterator_source(y); + const x: std.ForwardList = new std.ForwardList(); + const y: std.ForwardList = new std.ForwardList(); + + for (let i: number = 1; i <= 3; ++i) { + x.push_front(i); + y.push_front(i + 3); + } + x.swap(y); + + let sum: number = 0; + for (let it = x.begin(); !it.equals(x.end()); it = it.next()) sum += it.value; + + if (sum !== 4 + 5 + 6) + throw new Error(`Bug on ${x.constructor.name}.swap(); contents -> ${sum}`); + + _Validate_forward_list_iterator_source(x); + _Validate_forward_list_iterator_source(y); } function _Validate_forward_list_iterator_source( - source: std.ForwardList, + source: std.ForwardList, ): void { - for ( - let it = source.before_begin(); - !it.equals(source.end()); - it = it.next() - ) - if (it.source() !== source) - throw new Error( - `Bug on ${source.constructor.name}.swap(); source.`, - ); + for (let it = source.before_begin(); !it.equals(source.end()); it = it.next()) + if (it.source() !== source) + throw new Error(`Bug on ${source.constructor.name}.swap(); source.`); } diff --git a/src/test/container/test_trees.ts b/src/test/container/test_trees.ts index de95168f..36f5ed1d 100644 --- a/src/test/container/test_trees.ts +++ b/src/test/container/test_trees.ts @@ -2,157 +2,148 @@ import * as std from "../../index"; import { Temporary } from "../../internal/functional/Temporary"; export function test_trees(): void { - _Test_tree_set(new std.TreeSet()); - _Test_tree_set(new std.experimental.FlatSet()); - _Test_tree_set(new std.TreeMultiSet()); - _Test_tree_set(new std.experimental.FlatMultiSet()); + _Test_tree_set(new std.TreeSet()); + _Test_tree_set(new std.experimental.FlatSet()); + _Test_tree_set(new std.TreeMultiSet()); + _Test_tree_set(new std.experimental.FlatMultiSet()); - _Test_tree_map(new std.TreeMap()); - _Test_tree_map(new std.experimental.FlatMap()); - _Test_tree_map(new std.TreeMultiMap()); - _Test_tree_map(new std.experimental.FlatMultiMap()); + _Test_tree_map(new std.TreeMap()); + _Test_tree_map(new std.experimental.FlatMap()); + _Test_tree_map(new std.TreeMultiMap()); + _Test_tree_map(new std.experimental.FlatMultiMap()); - _Test_tree_set_inserts_and_erases(); + _Test_tree_set_inserts_and_erases(); } function _Test_tree_set_inserts_and_erases(): void { - for (let k = 0; k < 100; ++k) { - const set: std.TreeSet = new std.TreeSet(); - for (let i = 0; i < 100; ++i) set.insert(std.randint(0, 10000)); - - for (const val of set) - if (set.has(val) === false) - throw new Error( - `Bug on ${set.constructor.name}.has(): failed to detect stored element.`, - ); - - while (!set.empty()) { - const advance: number = std.randint(0, set.size() - 1); - const it: std.TreeSet.Iterator = std.advance( - set.begin(), - advance, - ); - - set.erase(it); - if (set.has(it.value)) - throw new Error( - `Bug on ${set.constructor.name}.has(): detected deleted element.`, - ); - } + for (let k = 0; k < 100; ++k) { + const set: std.TreeSet = new std.TreeSet(); + for (let i = 0; i < 100; ++i) set.insert(std.randint(0, 10000)); + + for (const val of set) + if (set.has(val) === false) + throw new Error( + `Bug on ${set.constructor.name}.has(): failed to detect stored element.`, + ); + + while (!set.empty()) { + const advance: number = std.randint(0, set.size() - 1); + const it: std.TreeSet.Iterator = std.advance( + set.begin(), + advance, + ); + + set.erase(it); + if (set.has(it.value)) + throw new Error( + `Bug on ${set.constructor.name}.has(): detected deleted element.`, + ); } + } } function _Test_tree_set< - Unique extends boolean, - Source extends std.base.ITreeSet< - number, - Unique, - Source, - IteratorT, - ReverseT - >, - IteratorT extends std.base.SetContainer.Iterator< - number, - Unique, - Source, - IteratorT, - ReverseT - >, - ReverseT extends std.base.SetContainer.ReverseIterator< - number, - Unique, - Source, - IteratorT, - ReverseT - >, + Unique extends boolean, + Source extends std.base.ITreeSet, + IteratorT extends std.base.SetContainer.Iterator< + number, + Unique, + Source, + IteratorT, + ReverseT + >, + ReverseT extends std.base.SetContainer.ReverseIterator< + number, + Unique, + Source, + IteratorT, + ReverseT + >, >(set: Source): void { - for (let i: number = 0; i < 1000; ++i) - set.push(Math.floor(Math.random() * 100)); + for (let i: number = 0; i < 1000; ++i) + set.push(Math.floor(Math.random() * 100)); + + // VALIDATE SORTING + if (std.ranges.is_sorted(set) === false) + throw new Error( + `Bug on ${set.constructor.name}: stored elements are not sorted.`, + ); - // VALIDATE SORTING - if (std.ranges.is_sorted(set) === false) + // VALIDATE FIND + for (let i: number = 0; i < 100; ++i) { + const val: number = Math.floor(Math.random() * 100); + + const alg_it: IteratorT = std.ranges.find(set, val) as Temporary; + const set_it: IteratorT = set.find(val); + + if (alg_it === set.end()) + if (set_it === set.end()) continue; + else throw new Error( - `Bug on ${set.constructor.name}: stored elements are not sorted.`, + `Bug on ${set.constructor.name}.find(): failed find anything.`, ); - - // VALIDATE FIND - for (let i: number = 0; i < 100; ++i) { - const val: number = Math.floor(Math.random() * 100); - - const alg_it: IteratorT = std.ranges.find( - set, - val, - ) as Temporary; - const set_it: IteratorT = set.find(val); - - if (alg_it === set.end()) - if (set_it === set.end()) continue; - else - throw new Error( - `Bug on ${set.constructor.name}.find(): failed find anything.`, - ); - else if (alg_it.value !== set_it.value) - throw new Error( - `Bug on ${set.constructor.name}.find(): found wrong element.`, - ); - } + else if (alg_it.value !== set_it.value) + throw new Error( + `Bug on ${set.constructor.name}.find(): found wrong element.`, + ); + } } function _Test_tree_map< - Unique extends boolean, - Source extends std.base.ITreeMap< - number, - number, - Unique, - Source, - IteratorT, - ReverseT - >, - IteratorT extends std.base.MapContainer.Iterator< - number, - number, - Unique, - Source, - IteratorT, - ReverseT - >, - ReverseT extends std.base.MapContainer.ReverseIterator< - number, - number, - Unique, - Source, - IteratorT, - ReverseT - >, + Unique extends boolean, + Source extends std.base.ITreeMap< + number, + number, + Unique, + Source, + IteratorT, + ReverseT + >, + IteratorT extends std.base.MapContainer.Iterator< + number, + number, + Unique, + Source, + IteratorT, + ReverseT + >, + ReverseT extends std.base.MapContainer.ReverseIterator< + number, + number, + Unique, + Source, + IteratorT, + ReverseT + >, >(map: Source): void { - for (let i: number = 0; i < 1000; ++i) - map.push(std.make_pair(Math.floor(Math.random() * 100), 0)); - - // VALIDATE SORTING - if (std.ranges.is_sorted(map) === false) + for (let i: number = 0; i < 1000; ++i) + map.push(std.make_pair(Math.floor(Math.random() * 100), 0)); + + // VALIDATE SORTING + if (std.ranges.is_sorted(map) === false) + throw new Error( + `Bug on ${map.constructor.name}: stored elements are not sorted.`, + ); + + // VALIDATE FIND + for (let i: number = 0; i < 100; ++i) { + const val: number = Math.floor(Math.random() * 100); + + const alg_it: IteratorT = std.ranges.find_if( + map, + (entry) => val === (entry as Temporary).first, + ) as Temporary; + const set_it = map.find(val); + + if (alg_it === map.end()) + if (set_it === map.end()) continue; + else throw new Error( - `Bug on ${map.constructor.name}: stored elements are not sorted.`, + `Bug on ${map.constructor.name}.find(): failed find anything.`, ); - - // VALIDATE FIND - for (let i: number = 0; i < 100; ++i) { - const val: number = Math.floor(Math.random() * 100); - - const alg_it: IteratorT = std.ranges.find_if( - map, - (entry) => val === (entry as Temporary).first, - ) as Temporary; - const set_it = map.find(val); - - if (alg_it === map.end()) - if (set_it === map.end()) continue; - else - throw new Error( - `Bug on ${map.constructor.name}.find(): failed find anything.`, - ); - else if (alg_it.first !== set_it.first) - throw new Error( - `Bug on ${map.constructor.name}.find(): found wrong element.`, - ); - } + else if (alg_it.first !== set_it.first) + throw new Error( + `Bug on ${map.constructor.name}.find(): found wrong element.`, + ); + } } diff --git a/src/test/container/test_vector_bools.ts b/src/test/container/test_vector_bools.ts index beb0cd24..63f8c4c2 100644 --- a/src/test/container/test_vector_bools.ts +++ b/src/test/container/test_vector_bools.ts @@ -1,152 +1,147 @@ import * as std from "../../index"; export function rand_bool(): boolean { - return Math.random() < 0.5 ? false : true; + return Math.random() < 0.5 ? false : true; } export function test_vector_bools() { - _Test_vector_bool_elements_io(); - _Test_vector_bool_flip(); + _Test_vector_bool_elements_io(); + _Test_vector_bool_flip(); } /* --------------------------------------------------------- ELEMENTS I/O --------------------------------------------------------- */ function _Test_vector_bool_elements_io() { - const v: std.Vector = new std.Vector(); - const d: std.Deque = new std.Deque(); - const l: std.List = new std.List(); - const vb: std.VectorBoolean = new std.VectorBoolean(); - - //---- - // PARTIAL TESTS - //---- - // INITIALIZE WITH 10 FALSES + const v: std.Vector = new std.Vector(); + const d: std.Deque = new std.Deque(); + const l: std.List = new std.List(); + const vb: std.VectorBoolean = new std.VectorBoolean(); + + //---- + // PARTIAL TESTS + //---- + // INITIALIZE WITH 10 FALSES + _Modify_bool_containers(vb, v, d, l, function (obj) { + obj.assign(10, false); + }); + + // REPEAT INSERTIONS + for (let i: number = 0; i < 100; ++i) { + const pos: number = std.randint(0, v.size()); + const size: number = std.randint(1, 10); + const value: boolean = rand_bool(); + _Modify_bool_containers(vb, v, d, l, function (obj) { - obj.assign(10, false); + obj.insert(std.advance(obj.begin(), pos), size, value); }); + _Validate_bool_containers(vb, v, d, l); + } - // REPEAT INSERTIONS - for (let i: number = 0; i < 100; ++i) { - const pos: number = std.randint(0, v.size()); - const size: number = std.randint(1, 10); - const value: boolean = rand_bool(); - - _Modify_bool_containers(vb, v, d, l, function (obj) { - obj.insert(std.advance(obj.begin(), pos), size, value); - }); - _Validate_bool_containers(vb, v, d, l); - } - - // REPEAT DELETIONS - for (let i: number = 0; i < 100; ++i) { - const first: number = std.randint(0, v.size() - 1); - const last: number = std.randint(first + 1, v.size()); - - _Modify_bool_containers(vb, v, d, l, function (obj) { - obj.erase( - std.advance(obj.begin(), first), - std.advance(obj.begin(), last), - ); - }); - _Validate_bool_containers(vb, v, d, l); - } - - //---- - // REPEATED INSERTIONS & DELETIONS KEEPING SIZE - //---- - // ASSIGN 10 FLAGS - const initial_value: boolean = rand_bool(); + // REPEAT DELETIONS + for (let i: number = 0; i < 100; ++i) { + const first: number = std.randint(0, v.size() - 1); + const last: number = std.randint(first + 1, v.size()); _Modify_bool_containers(vb, v, d, l, function (obj) { - obj.assign(100, initial_value); + obj.erase( + std.advance(obj.begin(), first), + std.advance(obj.begin(), last), + ); }); + _Validate_bool_containers(vb, v, d, l); + } + + //---- + // REPEATED INSERTIONS & DELETIONS KEEPING SIZE + //---- + // ASSIGN 10 FLAGS + const initial_value: boolean = rand_bool(); + + _Modify_bool_containers(vb, v, d, l, function (obj) { + obj.assign(100, initial_value); + }); + + // CHANGE VALUES RANDOMLY + for (let i: number = 0; i < 100; ++i) { + const index: number = std.randint(0, 99); + const value: boolean = rand_bool(); + + _Modify_bool_containers(vb, v, d, l, function (obj) { + std.advance(obj.begin(), index).value = value; + }); + _Validate_bool_containers(vb, v, d, l); + } + + // MASS DELETIONS AND INSERTIONS KEEPING SIZE + for (let i: number = 0; i < 100; ++i) { + // ERASE ELEMENTS + const first_index: number = std.randint(0, v.size() - 1); + const last_index: number = std.randint(first_index + 1, v.size()); + + if (v.empty() || first_index >= last_index) continue; - // CHANGE VALUES RANDOMLY - for (let i: number = 0; i < 100; ++i) { - const index: number = std.randint(0, 99); - const value: boolean = rand_bool(); - - _Modify_bool_containers(vb, v, d, l, function (obj) { - std.advance(obj.begin(), index).value = value; - }); - _Validate_bool_containers(vb, v, d, l); - } - - // MASS DELETIONS AND INSERTIONS KEEPING SIZE - for (let i: number = 0; i < 100; ++i) { - // ERASE ELEMENTS - const first_index: number = std.randint(0, v.size() - 1); - const last_index: number = std.randint(first_index + 1, v.size()); - - if (v.empty() || first_index >= last_index) continue; - - _Modify_bool_containers(vb, v, d, l, function (obj) { - obj.erase( - std.advance(obj.begin(), first_index), - std.advance(obj.begin(), last_index), - ); - }); - - // INSERT ELEMENTS - const index: number = std.randint(0, v.size()); - const size: number = last_index - first_index; - const value: boolean = rand_bool(); - - _Modify_bool_containers(vb, v, d, l, function (obj) { - obj.insert(std.advance(obj.begin(), index), size, value); - }); - _Validate_bool_containers(vb, v, d, l); - } + _Modify_bool_containers(vb, v, d, l, function (obj) { + obj.erase( + std.advance(obj.begin(), first_index), + std.advance(obj.begin(), last_index), + ); + }); + + // INSERT ELEMENTS + const index: number = std.randint(0, v.size()); + const size: number = last_index - first_index; + const value: boolean = rand_bool(); + + _Modify_bool_containers(vb, v, d, l, function (obj) { + obj.insert(std.advance(obj.begin(), index), size, value); + }); + _Validate_bool_containers(vb, v, d, l); + } } function _Validate_bool_containers( - vb: std.VectorBoolean, - v: std.Vector, - d: std.Deque, - l: std.List, + vb: std.VectorBoolean, + v: std.Vector, + d: std.Deque, + l: std.List, ): void { - for (const container of [v, d, l]) - if ( - vb.size() !== container.size() || - std.equal(vb.begin(), vb.end(), container.begin()) === false - ) - throw new Error( - `Bug on ${vb.constructor.name}: different elements are stored with ${container.constructor.name}`, - ); + for (const container of [v, d, l]) + if ( + vb.size() !== container.size() || + std.equal(vb.begin(), vb.end(), container.begin()) === false + ) + throw new Error( + `Bug on ${vb.constructor.name}: different elements are stored with ${container.constructor.name}`, + ); } function _Modify_bool_containers( - vb: std.VectorBoolean, - v: std.Vector, - d: std.Deque, - l: std.List, - func: ( - container: std.base.ILinearContainer, - ) => void, + vb: std.VectorBoolean, + v: std.Vector, + d: std.Deque, + l: std.List, + func: ( + container: std.base.ILinearContainer, + ) => void, ): void { - func(v); - func(d); - func(l); - func(vb); + func(v); + func(d); + func(l); + func(vb); } /* --------------------------------------------------------- FLIP --------------------------------------------------------- */ function _Test_vector_bool_flip() { - const vb = new std.VectorBoolean(); - for (let i: number = 0; i < 100; ++i) vb.push_back(rand_bool()); - - const cpy = new std.VectorBoolean(vb); - cpy.flip(); - - const valid = std.equal( - vb.begin(), - vb.end(), - cpy.begin(), - std.not_equal_to, - ); - if (valid === false) - throw new std.DomainError(`Bug on std.${vb.constructor.name}.flip().`); + const vb = new std.VectorBoolean(); + for (let i: number = 0; i < 100; ++i) vb.push_back(rand_bool()); + + const cpy = new std.VectorBoolean(vb); + cpy.flip(); + + const valid = std.equal(vb.begin(), vb.end(), cpy.begin(), std.not_equal_to); + if (valid === false) + throw new std.DomainError(`Bug on std.${vb.constructor.name}.flip().`); } diff --git a/src/test/exception/test_names.ts b/src/test/exception/test_names.ts index ac085a32..91caf19a 100644 --- a/src/test/exception/test_names.ts +++ b/src/test/exception/test_names.ts @@ -1,22 +1,22 @@ import * as std from "../../index"; const EXP_NAMES = [ - "Exception", - "LogicError", - "DomainError", - "LengthError", - "OutOfRange", - "RuntimeError", - "OverflowError", - "UnderflowError", + "Exception", + "LogicError", + "DomainError", + "LengthError", + "OutOfRange", + "RuntimeError", + "OverflowError", + "UnderflowError", ] as const; export function test_exception_names(): void { - for (const name of EXP_NAMES) { - const exp: std.Exception = new std[name]("Error Message"); - if (exp.name !== name) - throw new std.DomainError( - `Bug on ${exp.constructor.name}.name(): result is not ${name} bu ${exp.name}`, - ); - } + for (const name of EXP_NAMES) { + const exp: std.Exception = new std[name]("Error Message"); + if (exp.name !== name) + throw new std.DomainError( + `Bug on ${exp.constructor.name}.name(): result is not ${name} bu ${exp.name}`, + ); + } } diff --git a/src/test/functional/test_comparators.ts b/src/test/functional/test_comparators.ts index 7256c3ed..5e07bfc2 100644 --- a/src/test/functional/test_comparators.ts +++ b/src/test/functional/test_comparators.ts @@ -1,39 +1,28 @@ import * as std from "../../index"; - -import { Atomic } from "../internal/Atomic"; import { Comparator } from "../../internal/functional/Comparator"; +import { Atomic } from "../internal/Atomic"; export function test_comparisons(): void { - const atoms = new std.Vector>(); - for (let i: number = 0; i < 10; ++i) - for (let j: number = 0; j < 3; ++j) atoms.push(new Atomic(i)); + const atoms = new std.Vector>(); + for (let i: number = 0; i < 10; ++i) + for (let j: number = 0; j < 3; ++j) atoms.push(new Atomic(i)); - for (const x of atoms) - for (const y of atoms) { - _Test_comparison_results(x, y, x.value === y.value, std.equal_to); - _Test_comparison_results( - x, - y, - x.value !== y.value, - std.not_equal_to, - ); - _Test_comparison_results(x, y, x.value < y.value, std.less); - _Test_comparison_results(x, y, x.value > y.value, std.greater); - _Test_comparison_results(x, y, x.value <= y.value, std.less_equal); - _Test_comparison_results( - x, - y, - x.value >= y.value, - std.greater_equal, - ); - } + for (const x of atoms) + for (const y of atoms) { + _Test_comparison_results(x, y, x.value === y.value, std.equal_to); + _Test_comparison_results(x, y, x.value !== y.value, std.not_equal_to); + _Test_comparison_results(x, y, x.value < y.value, std.less); + _Test_comparison_results(x, y, x.value > y.value, std.greater); + _Test_comparison_results(x, y, x.value <= y.value, std.less_equal); + _Test_comparison_results(x, y, x.value >= y.value, std.greater_equal); + } } function _Test_comparison_results( - x: T, - y: T, - bit: boolean, - func: Comparator, + x: T, + y: T, + bit: boolean, + func: Comparator, ): void { - if (bit !== func(x, y)) throw new Error("Invalid comparison."); + if (bit !== func(x, y)) throw new Error("Invalid comparison."); } diff --git a/src/test/functional/test_hash.ts b/src/test/functional/test_hash.ts index d4df3a3a..d96be739 100644 --- a/src/test/functional/test_hash.ts +++ b/src/test/functional/test_hash.ts @@ -1,5 +1,5 @@ import * as std from "../../index"; export function test_hash(): void { - std.hash(1, 2, 3, {}, null, undefined, true); + std.hash(1, 2, 3, {}, null, undefined, true); } diff --git a/src/test/index.ts b/src/test/index.ts index 09571960..52f5777c 100644 --- a/src/test/index.ts +++ b/src/test/index.ts @@ -1,96 +1,96 @@ -const EXTENSION = (() => { - const index: number = __filename.lastIndexOf("."); - return __filename.substring(index + 1); +import * as cli from "cli"; +import * as fs from "fs"; + +const EXTENSION = (() => { + const index: number = __filename.lastIndexOf("."); + return __filename.substring(index + 1); })(); if (EXTENSION === "js" || EXTENSION === "mjs") - require("source-map-support").install(); - -import * as cli from "cli"; -import * as fs from "fs"; + require("source-map-support").install(); interface ICommand { - target?: string; - exclude?: string; + target?: string; + exclude?: string; } interface IModule { - [key: string]: () => Promise; + [key: string]: () => Promise; } async function measure(job: () => Promise): Promise { - const time: number = Date.now(); - await job(); - return Date.now() - time; + const time: number = Date.now(); + await job(); + return Date.now() - time; } async function iterate(command: ICommand, path: string): Promise { - const fileList: string[] = await fs.promises.readdir(path); - for (const file of fileList) { - const location: string = `${path}/${file}`; - const stats: fs.Stats = await fs.promises.lstat(location); + const fileList: string[] = await fs.promises.readdir(path); + for (const file of fileList) { + const location: string = `${path}/${file}`; + const stats: fs.Stats = await fs.promises.lstat(location); - if ( - stats.isDirectory() === true && - file !== "internal" && - file !== "manual" - ) { - await iterate(command, location); - continue; - } else if ( - file.substr(-(EXTENSION.length + 1)) !== `.${EXTENSION}` || - location === `${__dirname}/index.${EXTENSION}` - ) - continue; + if ( + stats.isDirectory() === true && + file !== "internal" && + file !== "manual" + ) { + await iterate(command, location); + continue; + } else if ( + file.substr(-(EXTENSION.length + 1)) !== `.${EXTENSION}` || + location === `${__dirname}/index.${EXTENSION}` + ) + continue; - const external: IModule = await import(location); - for (const key in external) { - // WHETHER TESTING TARGET OR NOT - if (key.substr(0, 5) !== "test_") continue; - if (command.exclude && command.exclude === key.substr(5)) continue; - if (command.target && command.target !== key.substr(5)) continue; + const external: IModule = await import(location); + for (const key in external) { + // WHETHER TESTING TARGET OR NOT + if (key.substr(0, 5) !== "test_") continue; + if (command.exclude && command.exclude === key.substr(5)) continue; + if (command.target && command.target !== key.substr(5)) continue; - // PRINT TITLE & ELAPSED TIME - process.stdout.write(" - " + key); + // PRINT TITLE & ELAPSED TIME + process.stdout.write(" - " + key); - const time: number = await measure(() => external[key]()); - console.log(`: ${time} ms`); - } + const time: number = await measure(() => external[key]()); + console.log(`: ${time} ms`); } + } } async function main(): Promise { - //---- - // DO TEST - //---- - console.log("=========================================================="); - console.log(" TSTL Test Automation Program"); - console.log("=========================================================="); + //---- + // DO TEST + //---- + console.log("=========================================================="); + console.log(" TSTL Test Automation Program"); + console.log("=========================================================="); - const command: ICommand = cli.parse(); - if (process.argv[2] && process.argv[2][0] !== "-") - command.target = process.argv[2]; + const command: ICommand = cli.parse(); + if (process.argv[2] && process.argv[2][0] !== "-") + command.target = process.argv[2]; - const time: number = await measure(() => iterate(command, __dirname)); + const time: number = await measure(() => iterate(command, __dirname)); - //---- - // TRACE BENCHMARK - //---- - // ELAPSED TIME - console.log("----------------------------------------------------------"); - console.log("Success"); - console.log(` - elapsed time: ${time} ms`); + //---- + // TRACE BENCHMARK + //---- + // ELAPSED TIME + console.log("----------------------------------------------------------"); + console.log("Success"); + console.log(` - elapsed time: ${time} ms`); - // MEMORY USAGE - const memory: NodeJS.MemoryUsage = process.memoryUsage(); - for (const property in memory) { - const amount: number = - memory[property as keyof NodeJS.MemoryUsage] / 10 ** 6; - console.log(` - ${property}: ${amount} MB`); - } - console.log("----------------------------------------------------------\n"); + // MEMORY USAGE + const memory: NodeJS.MemoryUsage = process.memoryUsage(); + for (const property in memory) { + const amount: number = + memory[property as keyof NodeJS.MemoryUsage] / 10 ** 6; + console.log(` - ${property}: ${amount} MB`); + } + console.log("----------------------------------------------------------\n"); } main().catch((e) => { - process.stdout.write("\n"); - console.log(e); + process.stdout.write("\n"); + console.log(e); - process.exit(1); + process.exit(1); }); diff --git a/src/test/internal/ArrayUtil.ts b/src/test/internal/ArrayUtil.ts index 13139817..487aed56 100644 --- a/src/test/internal/ArrayUtil.ts +++ b/src/test/internal/ArrayUtil.ts @@ -1,17 +1,17 @@ -import { equal_to } from "../../functional/comparators"; import { randint } from "../../algorithm/random"; +import { equal_to } from "../../functional/comparators"; export namespace ArrayUtil { - export function has( - elements: T[], - target: T, - predicator: (x: T, y: T) => boolean = equal_to, - ): boolean { - return elements.find((elem) => predicator(elem, target)) !== undefined; - } + export function has( + elements: T[], + target: T, + predicator: (x: T, y: T) => boolean = equal_to, + ): boolean { + return elements.find((elem) => predicator(elem, target)) !== undefined; + } - export function random(elements: readonly T[]): T { - const index: number = randint(0, elements.length - 1); - return elements[index]; - } + export function random(elements: readonly T[]): T { + const index: number = randint(0, elements.length - 1); + return elements[index]; + } } diff --git a/src/test/internal/Atomic.ts b/src/test/internal/Atomic.ts index 7192fc86..4c47c3e8 100644 --- a/src/test/internal/Atomic.ts +++ b/src/test/internal/Atomic.ts @@ -1,20 +1,20 @@ import * as std from "../../index"; export class Atomic implements std.IPointer, std.IComparable> { - public value: T; + public value: T; - public constructor(value: T) { - this.value = value; - } + public constructor(value: T) { + this.value = value; + } - public equals(obj: Atomic): boolean { - return std.equal_to(this.value, obj.value); - } + public equals(obj: Atomic): boolean { + return std.equal_to(this.value, obj.value); + } - public less(obj: Atomic): boolean { - return std.less(this.value, obj.value); - } - public hashCode(): number { - return std.hash(this.value); - } + public less(obj: Atomic): boolean { + return std.less(this.value, obj.value); + } + public hashCode(): number { + return std.hash(this.value); + } } diff --git a/src/test/internal/Cube.ts b/src/test/internal/Cube.ts index 761657eb..36e61434 100644 --- a/src/test/internal/Cube.ts +++ b/src/test/internal/Cube.ts @@ -1,61 +1,61 @@ import { randint } from "../../algorithm/random"; export class Cube { - // LENGTHS ON EACH DIMENSION - public width: number; - public height: number; - public length: number; - - // CO-ORDINATES - public x: number; - public y: number; - public z: number; - - public constructor(); - public constructor(width: number, height: number, length: number); - public constructor( - width: number, - height: number, - length: number, - x: number, - y: number, - z: number, - ); - - public constructor( - width: number = randint(0, 10), - height: number = randint(0, 10), - length: number = randint(0, 10), - x: number = randint(0, 100), - y: number = randint(0, 100), - z: number = randint(0, 100), - ) { - this.width = width; - this.height = height; - this.length = length; - - this.x = x; - this.y = y; - this.z = z; - } - - public get volume(): number { - return this.width * this.height * this.length; - } - - public less(obj: Cube): boolean { - return Cube.compare_volume(this, obj); - } + // LENGTHS ON EACH DIMENSION + public width: number; + public height: number; + public length: number; + + // CO-ORDINATES + public x: number; + public y: number; + public z: number; + + public constructor(); + public constructor(width: number, height: number, length: number); + public constructor( + width: number, + height: number, + length: number, + x: number, + y: number, + z: number, + ); + + public constructor( + width: number = randint(0, 10), + height: number = randint(0, 10), + length: number = randint(0, 10), + x: number = randint(0, 100), + y: number = randint(0, 100), + z: number = randint(0, 100), + ) { + this.width = width; + this.height = height; + this.length = length; + + this.x = x; + this.y = y; + this.z = z; + } + + public get volume(): number { + return this.width * this.height * this.length; + } + + public less(obj: Cube): boolean { + return Cube.compare_volume(this, obj); + } } export namespace Cube { - export function compare_volume(x: Cube, y: Cube): boolean { - return x.volume < y.volume; - } - - export function compare_position(left: Cube, right: Cube): boolean { - if (left.x !== right.x) return left.x < right.x; - else if (left.y !== right.y) return left.y < right.y; - else return left.z < right.z; - } + export function compare_volume(x: Cube, y: Cube): boolean { + return x.volume < y.volume; + } + + export function compare_position(left: Cube, right: Cube): boolean { + if (left.x !== right.x) return left.x < right.x; + else if (left.y !== right.y) return left.y < right.y; + else return left.z < right.z; + } } diff --git a/src/test/internal/Generator.ts b/src/test/internal/Generator.ts index e47e6eb1..d926981b 100644 --- a/src/test/internal/Generator.ts +++ b/src/test/internal/Generator.ts @@ -1,54 +1,53 @@ -import { Vector } from "../../container/Vector"; -import { Deque } from "../../container/Deque"; import { randint } from "../../algorithm/random"; import { sort } from "../../algorithm/sorting"; - -import { IForwardContainer } from "../../ranges/container/IForwardContainer"; +import { Deque } from "../../container/Deque"; +import { Vector } from "../../container/Vector"; import { IPush } from "../../internal/container/partial/IPush"; import { Temporary } from "../../internal/functional/Temporary"; +import { IForwardContainer } from "../../ranges/container/IForwardContainer"; export namespace Generator { - export function arrange | Deque>( - container: Container, - count: number, - ): Container; - - export function arrange | Deque>( - container: Container, - count: number, - gen: () => IForwardContainer.ValueType, - ): Container; - - export function arrange | Deque>( - container: Container, - count: number, - gen?: () => any, - ): Container { - fill(container, count, gen as Temporary); - sort(container.begin(), container.end()); - - return container; - } - - export function fill>( - container: Container, - count: number, - ): Container; - - export function fill>( - container: Container, - count: number, - gen: () => Container extends IPush ? T : unknown, - ): Container; - - export function fill>( - container: Container, - count: number, - gen?: () => any, - ): Container { - if (gen === undefined) gen = () => randint(1, count * 2); - - while (count-- > 0) container.push(gen()); - return container; - } + export function arrange | Deque>( + container: Container, + count: number, + ): Container; + + export function arrange | Deque>( + container: Container, + count: number, + gen: () => IForwardContainer.ValueType, + ): Container; + + export function arrange | Deque>( + container: Container, + count: number, + gen?: () => any, + ): Container { + fill(container, count, gen as Temporary); + sort(container.begin(), container.end()); + + return container; + } + + export function fill>( + container: Container, + count: number, + ): Container; + + export function fill>( + container: Container, + count: number, + gen: () => Container extends IPush ? T : unknown, + ): Container; + + export function fill>( + container: Container, + count: number, + gen?: () => any, + ): Container { + if (gen === undefined) gen = () => randint(1, count * 2); + + while (count-- > 0) container.push(gen()); + return container; + } } diff --git a/src/test/internal/Point2D.ts b/src/test/internal/Point2D.ts index cbae2dd2..e1018cbe 100644 --- a/src/test/internal/Point2D.ts +++ b/src/test/internal/Point2D.ts @@ -1,37 +1,37 @@ import * as std from "../../index"; export class Point2D - implements - Pick, "equals">, - Pick< - std.IComputable, - "plus" | "minus" | "multiplies" - > + implements + Pick, "equals">, + Pick< + std.IComputable, + "plus" | "minus" | "multiplies" + > { - public x: number; - public y: number; + public x: number; + public y: number; - public constructor(x: number = 0, y: number = 0) { - this.x = x; - this.y = y; - } - public equals(obj: Point2D): boolean { - return this.x === obj.x && this.y === obj.y; - } + public constructor(x: number = 0, y: number = 0) { + this.x = x; + this.y = y; + } + public equals(obj: Point2D): boolean { + return this.x === obj.x && this.y === obj.y; + } - public plus(val: number | Point2D): Point2D { - if (val instanceof Point2D) - return new Point2D(this.x + val.x, this.y + val.y); - else return new Point2D(this.x + val, this.y + val); - } - public minus(val: number | Point2D): Point2D { - if (val instanceof Point2D) - return new Point2D(this.x - val.x, this.y - val.y); - else return new Point2D(this.x - val, this.y - val); - } - public multiplies(val: number | Point2D): Point2D { - if (val instanceof Point2D) - return new Point2D(this.x * val.x, this.y * val.y); - else return new Point2D(this.x * val, this.y * val); - } + public plus(val: number | Point2D): Point2D { + if (val instanceof Point2D) + return new Point2D(this.x + val.x, this.y + val.y); + else return new Point2D(this.x + val, this.y + val); + } + public minus(val: number | Point2D): Point2D { + if (val instanceof Point2D) + return new Point2D(this.x - val.x, this.y - val.y); + else return new Point2D(this.x - val, this.y - val); + } + public multiplies(val: number | Point2D): Point2D { + if (val instanceof Point2D) + return new Point2D(this.x * val.x, this.y * val.y); + else return new Point2D(this.x * val, this.y * val); + } } diff --git a/src/test/iterator/test_inserters.ts b/src/test/iterator/test_inserters.ts index 6e9acf92..76397b0c 100644 --- a/src/test/iterator/test_inserters.ts +++ b/src/test/iterator/test_inserters.ts @@ -1,17 +1,17 @@ import * as std from "../../index"; export function test_inserters(): void { - const s: std.TreeSet = new std.TreeSet(); - const v: std.Vector = new std.Vector(); + const s: std.TreeSet = new std.TreeSet(); + const v: std.Vector = new std.Vector(); - v.push_back(1); - v.push_back(2); + v.push_back(1); + v.push_back(2); - std.set_union( - s.begin(), - s.end(), - v.begin(), - v.end(), - std.inserter(s, s.end()), - ); + std.set_union( + s.begin(), + s.end(), + v.begin(), + v.end(), + std.inserter(s, s.end()), + ); } diff --git a/src/test/manual/70.ts b/src/test/manual/70.ts index 0f38ca2f..0e1b5425 100644 --- a/src/test/manual/70.ts +++ b/src/test/manual/70.ts @@ -1,32 +1,32 @@ -import { Semaphore } from "../../thread/Semaphore"; import { randint } from "../../algorithm/random"; +import { Semaphore } from "../../thread/Semaphore"; import { sleep_for } from "../../thread/global"; async function main(): Promise { - const s: Semaphore = new Semaphore(4); - const minimum: number = 500; - const maximum: number = 4000; + const s: Semaphore = new Semaphore(4); + const minimum: number = 500; + const maximum: number = 4000; - while (true) { - let waitTime: number = Date.now(); - const success: boolean = await s.try_acquire_for(1000); - waitTime = Date.now() - waitTime; + while (true) { + let waitTime: number = Date.now(); + const success: boolean = await s.try_acquire_for(1000); + waitTime = Date.now() - waitTime; - if (success === true) { - (async () => { - const sleepTime: number = randint(minimum, maximum); - console.log( - "success, sleep_for", - sleepTime, - "ms after", - waitTime, - "ms", - ); + if (success === true) { + (async () => { + const sleepTime: number = randint(minimum, maximum); + console.log( + "success, sleep_for", + sleepTime, + "ms after", + waitTime, + "ms", + ); - await sleep_for(sleepTime); - await s.release(); - })(); - } else console.log("failed after", waitTime, "ms"); - } + await sleep_for(sleepTime); + await s.release(); + })(); + } else console.log("failed after", waitTime, "ms"); + } } main(); diff --git a/src/test/numeric/special_math/data.json b/src/test/numeric/special_math/data.json index 4a88779b..08f775f5 100644 --- a/src/test/numeric/special_math/data.json +++ b/src/test/numeric/special_math/data.json @@ -1,1503 +1,1503 @@ [ - ["cyl_bessel_i", -8.22945, 2.22939, 582.734], - ["cyl_bessel_j", -8.22945, 2.22939, 821.955], - ["cyl_bessel_k", -8.22945, 2.22939, 1386.88], - ["cyl_neumann", -8.22945, 2.22939, -935.585], - ["sph_bessel", 1, 2.22939, 0.433637], - ["sph_neumann", 1, 2.22939, -0.231604], - ["cyl_bessel_i", -2, -8.60511, 589.337], - ["cyl_bessel_j", -2, -8.60511, 0.0501442], - ["cyl_bessel_k", -1.95539, 8.60511, 9.52189e-05], - ["cyl_neumann", -1.95539, 8.60511, -0.273857], - ["sph_bessel", 0, 8.60511, 0.0849398], - ["sph_neumann", 0, 8.60511, 0.0793094], - ["cyl_bessel_i", -6.70685, 5.95949, 1.61543], - ["cyl_bessel_j", -6.70685, 5.95949, 0.376504], - ["cyl_bessel_k", -6.70685, 5.95949, 0.0348366], - ["cyl_neumann", -6.70685, 5.95949, 0.481466], - ["sph_bessel", 2, 5.95949, -0.0312186], - ["sph_neumann", 2, 5.95949, 0.172515], - ["cyl_bessel_i", -9.7301, 7.68293, 0.908489], - ["cyl_bessel_j", -9.7301, 7.68293, -0.678491], - ["cyl_bessel_k", -9.7301, 7.68293, 0.0433752], - ["cyl_neumann", -9.7301, 7.68293, -0.675836], - ["sph_bessel", 0, 7.68293, 0.128259], - ["sph_neumann", 0, 7.68293, -0.0221551], - ["cyl_bessel_i", -2.06486, 0.603805, 0.767621], - ["cyl_bessel_j", -2.06486, 0.603805, 0.899114], - ["cyl_bessel_k", -2.06486, 0.603805, 5.64132], - ["cyl_neumann", -2.06486, 0.603805, -4.16093], - ["sph_bessel", 7, 0.603805, 1.42809e-08], - ["sph_neumann", 7, 0.603805, -7.75701e+06], - ["cyl_bessel_i", 8.62319, 9.15733, 23.4759], - ["cyl_bessel_j", 8.62319, 9.15733, 0.264633], - ["cyl_bessel_k", 8.62319, 9.15733, 0.0016923], - ["cyl_neumann", 8.62319, 9.15733, -0.283982], - ["sph_bessel", 7, 9.15733, 0.136994], - ["sph_neumann", 7, 9.15733, -0.0261161], - ["cyl_bessel_i", 9, -0.328577, -2.40921e-13], - ["cyl_bessel_j", 9, -0.328577, -2.39624e-13], - ["cyl_bessel_k", 9.32857, 0.328577, 8.48266e+11], - ["cyl_neumann", 9.32857, 0.328577, -5.43535e+11], - ["sph_bessel", 6, 0.328577, 9.27881e-09], - ["sph_neumann", 6, 0.328577, -2.52637e+07], - ["cyl_bessel_i", 4, -6.30895, 23.6382], - ["cyl_bessel_j", 4, -6.30895, 0.3112], - ["cyl_bessel_k", 4.76613, 6.30895, 0.00452921], - ["cyl_neumann", 4.76613, 6.30895, -0.0486063], - ["sph_bessel", 6, 6.30895, 0.108794], - ["sph_neumann", 6, 6.30895, -0.228437], - ["cyl_bessel_i", -8, -3.30098, 0.00184039], - ["cyl_bessel_j", -8, -3.30098, 0.00100429], - ["cyl_bessel_k", -7.88289, 3.30098, 26.1357], - ["cyl_neumann", -7.88289, 3.30098, -34.3665], - ["sph_bessel", 1, 3.30098, 0.284536], - ["sph_neumann", 1, 3.30098, 0.138689], - ["cyl_bessel_i", -10, -0.507934, 3.09428e-13], - ["cyl_bessel_j", -10, -0.507934, 3.05821e-13], - ["cyl_bessel_k", -9.47574, 0.507934, 2.45082e+10], - ["cyl_neumann", -9.47574, 0.507934, 1.20617e+09], - ["sph_bessel", 9, 0.507934, 3.41617e-12], - ["sph_neumann", 9, 0.507934, -3.03758e+10], - ["cyl_bessel_i", 8.95185, 9.40842, 24.7422], - ["cyl_bessel_j", 8.95185, 9.40842, 0.254767], - ["cyl_bessel_k", 8.95185, 9.40842, 0.00155526], - ["cyl_neumann", 8.95185, 9.40842, -0.295027], - ["sph_bessel", 5, 9.40842, -0.0050529], - ["sph_neumann", 5, 9.40842, 0.117315], - ["cyl_bessel_i", -6.2007, 6.22679, 3.81316], - ["cyl_bessel_j", -6.2007, 6.22679, 0.444251], - ["cyl_bessel_k", -6.2007, 6.22679, 0.0149256], - ["cyl_neumann", -6.2007, 6.22679, -0.191143], - ["sph_bessel", 0, 6.22679, -0.00905235], - ["sph_neumann", 0, 6.22679, -0.160341], - ["cyl_bessel_i", 8.96131, 7.97894, 3.2635], - ["cyl_bessel_j", 8.96131, 7.97894, 0.127826], - ["cyl_bessel_k", 8.96131, 7.97894, 0.0127601], - ["cyl_neumann", 8.96131, 7.97894, -0.571977], - ["sph_bessel", 1, 7.97894, 0.0312054], - ["sph_neumann", 1, 7.97894, -0.122395], - ["cyl_bessel_i", -9, -9.30887, -20.7158], - ["cyl_bessel_j", -9, -9.30887, 0.242028], - ["cyl_bessel_k", -8.27207, 9.30887, 0.00103801], - ["cyl_neumann", -8.27207, 9.30887, 0.102256], - ["sph_bessel", 7, 9.30887, 0.135061], - ["sph_neumann", 7, 9.30887, -0.0127884], - ["cyl_bessel_i", 2.67713, 1.64132, 0.173622], - ["cyl_bessel_j", 2.67713, 1.64132, 0.120333], - ["cyl_bessel_k", 2.67713, 1.64132, 0.909297], - ["cyl_neumann", 2.67713, 1.64132, -1.28718], - ["sph_bessel", 0, 1.64132, 0.60775], - ["sph_neumann", 0, 1.64132, 0.0429334], - ["cyl_bessel_i", -4, -3.04496, 0.350084], - ["cyl_bessel_j", -4, -3.04496, 0.138073], - ["cyl_bessel_k", -3.37257, 3.04496, 0.156158], - ["cyl_neumann", -3.37257, 3.04496, 0.0268717], - ["sph_bessel", 7, 3.04496, 0.000907869], - ["sph_neumann", 7, 3.04496, -26.4652], - ["cyl_bessel_i", -5, -7.73585, -63.2894], - ["cyl_bessel_j", -5, -7.73585, 0.240928], - ["cyl_bessel_k", -4.42534, 7.73585, 0.000624919], - ["cyl_neumann", -4.42534, 7.73585, 0.160469], - ["sph_bessel", 10, 7.73585, 0.0140547], - ["sph_neumann", 10, 7.73585, -0.667576], - ["cyl_bessel_i", 9.79562, 0.663139, 9.04206e-12], - ["cyl_bessel_j", 9.79562, 0.663139, 8.85976e-12], - ["cyl_bessel_k", 9.79562, 0.663139, 5.63206e+09], - ["cyl_neumann", 9.79562, 0.663139, -3.67624e+09], - ["sph_bessel", 3, 0.663139, 0.00271014], - ["sph_neumann", 3, 0.663139, -81.1107], - ["cyl_bessel_i", -0.658851, 8.69203, 796.805], - ["cyl_bessel_j", -0.658851, 8.69203, -0.2411], - ["cyl_bessel_k", -0.658851, 8.69203, 7.21036e-05], - ["cyl_neumann", -0.658851, 8.69203, 0.12329], - ["sph_bessel", 6, 8.69203, 0.135549], - ["sph_neumann", 6, 8.69203, 0.0290624], - ["cyl_bessel_i", -3, -7.05845, -90.444], - ["cyl_bessel_j", -3, -7.05845, -0.180681], - ["cyl_bessel_k", -2.46092, 7.05845, 0.000595037], - ["cyl_neumann", -2.46092, 7.05845, -0.27916], - ["sph_bessel", 6, 7.05845, 0.139847], - ["sph_neumann", 6, 7.05845, -0.139775], - ["cyl_bessel_i", -9, -1.6091, -4.15188e-07], - ["cyl_bessel_j", -9, -1.6091, 3.64771e-07], - ["cyl_bessel_k", -8.38449, 1.6091, 31351.1], - ["cyl_neumann", -8.38449, 1.6091, -8442.74], - ["sph_bessel", 10, 1.6091, 7.99927e-09], - ["sph_neumann", 10, 1.6091, -3.74419e+06], - ["cyl_bessel_i", -8, -9.78718, 88.8396], - ["cyl_bessel_j", -8, -9.78718, 0.323376], - ["cyl_bessel_k", -7.57722, 9.78718, 0.000330236], - ["cyl_neumann", -7.57722, 9.78718, -0.28924], - ["sph_bessel", 6, 9.78718, 0.0626841], - ["sph_neumann", 6, 9.78718, 0.0990758], - ["cyl_bessel_i", 6.37191, 3.68549, 0.0527286], - ["cyl_bessel_j", 6.37191, 3.68549, 0.0209519], - ["cyl_bessel_k", 6.37191, 3.68549, 1.2862], - ["cyl_neumann", 6.37191, 3.68549, -2.9783], - ["sph_bessel", 1, 3.68549, 0.194084], - ["sph_neumann", 1, 3.68549, 0.203407], - ["cyl_bessel_i", 5.44232, 8.02878, 66.5237], - ["cyl_bessel_j", 5.44232, 8.02878, 0.271855], - ["cyl_bessel_k", 5.44232, 8.02878, 0.000774483], - ["cyl_neumann", 5.44232, 8.02878, 0.177208], - ["sph_bessel", 9, 8.02878, 0.0403048], - ["sph_neumann", 9, 8.02878, -0.309241], - ["cyl_bessel_i", -3, -9.10705, -720.003], - ["cyl_bessel_j", -3, -9.10705, -0.158221], - ["cyl_bessel_k", -2.86788, 9.10705, 6.96325e-05], - ["cyl_neumann", -2.86788, 9.10705, 0.17432], - ["sph_bessel", 10, 9.10705, 0.0400525], - ["sph_neumann", 10, 9.10705, -0.262887], - ["cyl_bessel_i", 5.32167, 1.76282, 0.00275211], - ["cyl_bessel_j", 5.32167, 1.76282, 0.00215231], - ["cyl_bessel_k", 5.32167, 1.76282, 32.3629], - ["cyl_neumann", 5.32167, 1.76282, -29.5485], - ["sph_bessel", 6, 1.76282, 0.000200087], - ["sph_neumann", 6, 1.76282, -226.846], - ["cyl_bessel_i", 7.98608, 4.80589, 0.0523349], - ["cyl_bessel_j", 7.98608, 4.80589, 0.0144294], - ["cyl_bessel_k", 7.98608, 4.80589, 1.02399], - ["cyl_neumann", 7.98608, 4.80589, -3.51129], - ["sph_bessel", 0, 4.80589, -0.207169], - ["sph_neumann", 0, 4.80589, -0.0194281], - ["cyl_bessel_i", 4.72929, 7.10757, 36.6466], - ["cyl_bessel_j", 4.72929, 7.10757, 0.302032], - ["cyl_bessel_k", 4.72929, 7.10757, 0.00159711], - ["cyl_neumann", 4.72929, 7.10757, 0.160144], - ["sph_bessel", 5, 7.10757, 0.1702], - ["sph_neumann", 5, 7.10757, -0.0216967], - ["cyl_bessel_i", 0, -7.84614, 370.3], - ["cyl_bessel_j", 0, -7.84614, 0.205918], - ["cyl_bessel_k", 0.378608, 7.84614, 0.000173945], - ["cyl_neumann", 0.378608, 7.84614, 0.0498821], - ["sph_bessel", 3, 7.84614, -0.0927464], - ["sph_neumann", 3, 7.84614, 0.0971267], - ["cyl_bessel_i", -5, -9.62295, -516.817], - ["cyl_bessel_j", -5, -9.62295, -0.182905], - ["cyl_bessel_k", -4.84577, 9.62295, 8.29446e-05], - ["cyl_neumann", -4.84577, 9.62295, -0.254573], - ["sph_bessel", 10, 9.62295, 0.0537971], - ["sph_neumann", 10, 9.62295, -0.204458], - ["cyl_bessel_i", 3, -1.63886, -0.10817], - ["cyl_bessel_j", 3, -1.63886, -0.0773049], - ["cyl_bessel_k", 3.81265, 1.63886, 4.06086], - ["cyl_neumann", 3.81265, 1.63886, -4.20015], - ["sph_bessel", 4, 1.63886, 0.00674844], - ["sph_neumann", 4, 1.63886, -10.8569], - ["cyl_bessel_i", -4.59451, 9.43359, 517.613], - ["cyl_bessel_j", -4.59451, 9.43359, -0.0800797], - ["cyl_bessel_k", -4.59451, 9.43359, 9.20612e-05], - ["cyl_neumann", -4.59451, 9.43359, -0.265383], - ["sph_bessel", 0, 9.43359, -0.000934566], - ["sph_neumann", 0, 9.43359, 0.106], - ["cyl_bessel_i", -5, -2.21913, -0.0171567], - ["cyl_bessel_j", -5, -2.21913, 0.0113794], - ["cyl_bessel_k", -4.11935, 2.21913, 1.57664], - ["cyl_neumann", -4.11935, 2.21913, -2.08678], - ["sph_bessel", 10, 2.21913, 1.89171e-07], - ["sph_neumann", 10, 2.21913, -116083], - ["cyl_bessel_i", -1, -2.46505, -2.43812], - ["cyl_bessel_j", -1, -2.46505, 0.505539], - ["cyl_bessel_k", -0.947493, 2.46505, 0.0758422], - ["cyl_neumann", -0.947493, 2.46505, -0.0778582], - ["sph_bessel", 3, 2.46505, 0.100655], - ["sph_neumann", 3, 2.46505, -0.826162], - ["cyl_bessel_i", -9, -5.87524, -0.103164], - ["cyl_bessel_j", -9, -5.87524, 0.0182431], - ["cyl_bessel_k", -8.79749, 5.87524, 0.355913], - ["cyl_neumann", -8.79749, 5.87524, 1.78094], - ["sph_bessel", 8, 5.87524, 0.015894], - ["sph_neumann", 8, 5.87524, -0.896546], - ["cyl_bessel_i", -9, -8.25974, -4.73931], - ["cyl_bessel_j", -9, -8.25974, 0.148174], - ["cyl_bessel_k", -8.91871, 8.25974, 0.00801487], - ["cyl_neumann", -8.91871, 8.25974, 0.52102], - ["sph_bessel", 6, 8.25974, 0.149451], - ["sph_neumann", 6, 8.25974, -0.0118069], - ["cyl_bessel_i", -9.52125, 5.81788, -0.549704], - ["cyl_bessel_j", -9.52125, 5.81788, -4.49319], - ["cyl_bessel_k", -9.52125, 5.81788, 0.940366], - ["cyl_neumann", -9.52125, 5.81788, -0.309867], - ["sph_bessel", 5, 5.81788, 0.150915], - ["sph_neumann", 5, 5.81788, -0.18871], - ["cyl_bessel_i", 6, -2.84868, 0.0154181], - ["cyl_bessel_j", 6, -2.84868, 0.00863176], - ["cyl_bessel_k", 6.49451, 2.84868, 10.0404], - ["cyl_neumann", 6.49451, 2.84868, -13.4401], - ["sph_bessel", 10, 2.84868, 2.14285e-06], - ["sph_neumann", 10, 2.84868, -8108.42], - ["cyl_bessel_i", 6, -5.24377, 1.14257], - ["cyl_bessel_j", 6, -5.24377, 0.157381], - ["cyl_bessel_k", 6.87921, 5.24377, 0.130792], - ["cyl_neumann", 6.87921, 5.24377, -0.971137], - ["sph_bessel", 2, 5.24377, 0.0911837], - ["sph_neumann", 2, 5.24377, 0.180149], - ["cyl_bessel_i", 0.362031, 1.11278, 1.12922], - ["cyl_bessel_j", 0.362031, 1.11278, 0.715306], - ["cyl_bessel_k", 0.362031, 1.11278, 0.37528], - ["cyl_neumann", 0.362031, 1.11278, -0.209679], - ["sph_bessel", 4, 1.11278, 0.00153342], - ["sph_neumann", 4, 1.11278, -67.3429], - ["cyl_bessel_i", 2, -7.22511, 154.351], - ["cyl_bessel_j", 2, -7.22511, -0.276588], - ["cyl_bessel_k", 2.2542, 7.22511, 0.000463835], - ["cyl_neumann", 2.2542, 7.22511, -0.0275572], - ["sph_bessel", 5, 7.22511, 0.167217], - ["sph_neumann", 5, 7.22511, -0.0078814], - ["cyl_bessel_i", -4.4206, 9.76369, 798.377], - ["cyl_bessel_j", -4.4206, 9.76369, -0.094454], - ["cyl_bessel_k", -4.4206, 9.76369, 5.84398e-05], - ["cyl_neumann", -4.4206, 9.76369, -0.25276], - ["sph_bessel", 3, 9.76369, -0.0610195], - ["sph_neumann", 3, 9.76369, -0.0864953], - ["cyl_bessel_i", 5, -8.51223, -152.236], - ["cyl_bessel_j", 5, -8.51223, -0.0641093], - ["cyl_bessel_k", 5.18537, 8.51223, 0.000367838], - ["cyl_neumann", 5.18537, 8.51223, 0.282322], - ["sph_bessel", 10, 8.51223, 0.0266945], - ["sph_neumann", 10, 8.51223, -0.371547], - ["cyl_bessel_i", 4.38995, 6.85753, 34.3079], - ["cyl_bessel_j", 4.38995, 6.85753, 0.28507], - ["cyl_bessel_k", 4.38995, 6.85753, 0.00178876], - ["cyl_neumann", 4.38995, 6.85753, 0.191756], - ["sph_bessel", 7, 6.85753, 0.0779504], - ["sph_neumann", 7, 6.85753, -0.255544], - ["cyl_bessel_i", 1.39952, 3.65061, 6.11313], - ["cyl_bessel_j", 1.39952, 3.65061, 0.269348], - ["cyl_bessel_k", 1.39952, 3.65061, 0.0209586], - ["cyl_neumann", 1.39952, 3.65061, 0.335957], - ["sph_bessel", 5, 3.65061, 0.0366524], - ["sph_neumann", 5, 3.65061, -0.941477], - ["cyl_bessel_i", -7.20821, 1.37525, -2849.36], - ["cyl_bessel_j", -7.20821, 1.37525, -3318.27], - ["cyl_bessel_k", -7.20821, 1.37525, 7355.99], - ["cyl_neumann", -7.20821, 1.37525, 4327.96], - ["sph_bessel", 0, 1.37525, 0.713283], - ["sph_neumann", 0, 1.37525, -0.141286], - ["cyl_bessel_i", 4.07478, 0.606964, 0.000293959], - ["cyl_bessel_j", 4.07478, 0.606964, 0.00028348], - ["cyl_bessel_k", 4.07478, 0.606964, 412.602], - ["cyl_neumann", 4.07478, 0.606964, -278.892], - ["sph_bessel", 8, 0.606964, 5.29399e-10], - ["sph_neumann", 8, 0.606964, -1.8354e+08], - ["cyl_bessel_i", 0.30233, 0.922756, 1.03325], - ["cyl_bessel_j", 0.30233, 0.922756, 0.744555], - ["cyl_bessel_k", 0.30233, 0.922756, 0.487755], - ["cyl_neumann", 0.30233, 0.922756, -0.318843], - ["sph_bessel", 9, 0.922756, 7.25951e-10], - ["sph_neumann", 9, 0.922756, -7.89467e+07], - ["cyl_bessel_i", -7, -2.40931, -0.000874213], - ["cyl_bessel_j", -7, -2.40931, 0.000608159], - ["cyl_bessel_k", -6.00016, 2.40931, 14.8294], - ["cyl_neumann", -6.00016, 2.40931, -16.9195], - ["sph_bessel", 6, 2.40931, 0.00119008], - ["sph_neumann", 6, 2.40931, -28.9702], - ["cyl_bessel_i", -9, -2.22862, -8.25894e-06], - ["cyl_bessel_j", -9, -2.22862, 6.44264e-06], - ["cyl_bessel_k", -8.83124, 2.22862, 4625], - ["cyl_neumann", -8.83124, 2.22862, 3488.49], - ["sph_bessel", 0, 2.22862, 0.355072], - ["sph_neumann", 0, 2.22862, 0.274339], - ["cyl_bessel_i", -5, -6.4547, -13.9761], - ["cyl_bessel_j", -5, -6.4547, 0.37398], - ["cyl_bessel_k", -4.38636, 6.4547, 0.00295444], - ["cyl_neumann", -4.38636, 6.4547, 0.359627], - ["sph_bessel", 6, 6.4547, 0.115618], - ["sph_neumann", 6, 6.4547, -0.209864], - ["cyl_bessel_i", -3, -4.18761, -4.15215], - ["cyl_bessel_j", -3, -4.18761, 0.434375], - ["cyl_bessel_k", -2.91715, 4.18761, 0.022177], - ["cyl_neumann", -2.91715, 4.18761, 0.194412], - ["sph_bessel", 5, 4.18761, 0.060996], - ["sph_neumann", 5, 4.18761, -0.563614], - ["cyl_bessel_i", -8, -9.37862, 52.8172], - ["cyl_bessel_j", -8, -9.37862, 0.320845], - ["cyl_bessel_k", -7.30167, 9.37862, 0.000464247], - ["cyl_neumann", -7.30167, 9.37862, -0.276694], - ["sph_bessel", 9, 9.37862, 0.0820221], - ["sph_neumann", 9, 9.37862, -0.158127], - ["cyl_bessel_i", -8.32791, 5.17016, 0.484525], - ["cyl_bessel_j", -8.32791, 5.17016, 2.69568], - ["cyl_bessel_k", -8.32791, 5.17016, 0.765773], - ["cyl_neumann", -8.32791, 5.17016, -1.59978], - ["sph_bessel", 7, 5.17016, 0.021403], - ["sph_neumann", 7, 5.17016, -0.858511], - ["cyl_bessel_i", -8.60378, 8.61616, 11.414], - ["cyl_bessel_j", -8.60378, 8.61616, 0.286105], - ["cyl_bessel_k", -8.60378, 8.61616, 0.00359605], - ["cyl_neumann", -8.60378, 8.61616, 0.328193], - ["sph_bessel", 4, 8.61616, -0.0451936], - ["sph_neumann", 4, 8.61616, 0.116743], - ["cyl_bessel_i", -3, -3.02862, -0.997158], - ["cyl_bessel_j", -3, -3.02862, 0.314104], - ["cyl_bessel_k", -2.22897, 3.02862, 0.0677352], - ["cyl_neumann", -2.22897, 3.02862, 0.116108], - ["sph_bessel", 0, 3.02862, 0.037223], - ["sph_neumann", 0, 3.02862, 0.328079], - ["cyl_bessel_i", 4.51373, 3.78436, 0.618056], - ["cyl_bessel_j", 4.51373, 3.78436, 0.167374], - ["cyl_bessel_k", 4.51373, 3.78436, 0.136957], - ["cyl_neumann", 4.51373, 3.78436, -0.713284], - ["sph_bessel", 8, 3.78436, 0.000831532], - ["sph_neumann", 8, 3.78436, -20.9409], - ["cyl_bessel_i", -3.60386, 2.84588, 0.243414], - ["cyl_bessel_j", -3.60386, 2.84588, -0.724026], - ["cyl_bessel_k", -3.60386, 2.84588, 0.267719], - ["cyl_neumann", -3.60386, 2.84588, -0.421797], - ["sph_bessel", 9, 2.84588, 1.53967e-05], - ["sph_neumann", 9, 2.84588, -1259.85], - ["cyl_bessel_i", -5.75359, 9.72933, 382.911], - ["cyl_bessel_j", -5.75359, 9.72933, 0.184816], - ["cyl_bessel_k", -5.75359, 9.72933, 0.000115497], - ["cyl_neumann", -5.75359, 9.72933, 0.214955], - ["sph_bessel", 4, 9.72933, -0.106131], - ["sph_neumann", 4, 9.72933, 0.0244245], - ["cyl_bessel_i", -6.38851, 1.07125, 3611.61], - ["cyl_bessel_j", -6.38851, 1.07125, 4017.46], - ["cyl_bessel_k", -6.38851, 1.07125, 6039.79], - ["cyl_neumann", -6.38851, 1.07125, -1467.61], - ["sph_bessel", 2, 1.07125, 0.0704305], - ["sph_neumann", 2, 1.07125, -3.01657], - ["cyl_bessel_i", -3, -5.17516, -12.5037], - ["cyl_bessel_j", -3, -5.17516, 0.331681], - ["cyl_bessel_k", -2.53716, 5.17516, 0.00535694], - ["cyl_neumann", -2.53716, 5.17516, 0.163107], - ["sph_bessel", 8, 5.17516, 0.00719078], - ["sph_neumann", 8, 5.17516, -2.02119], - ["cyl_bessel_i", 1.83729, 2.4805, 1.42753], - ["cyl_bessel_j", 1.83729, 2.4805, 0.477004], - ["cyl_bessel_k", 1.83729, 2.4805, 0.112671], - ["cyl_neumann", 1.83729, 2.4805, -0.3184], - ["sph_bessel", 5, 2.4805, 0.00710255], - ["sph_neumann", 5, 2.4805, -5.83239], - ["cyl_bessel_i", -7.87681, 4.09759, -0.914328], - ["cyl_bessel_j", -7.87681, 4.09759, -3.18184], - ["cyl_bessel_k", -7.87681, 4.09759, 3.86585], - ["cyl_neumann", -7.87681, 4.09759, -7.82173], - ["sph_bessel", 8, 4.09759, 0.00146813], - ["sph_neumann", 8, 4.09759, -11.2088], - ["cyl_bessel_i", -8, -2.22243, 6.60755e-05], - ["cyl_bessel_j", -8, -2.22243, 5.02177e-05], - ["cyl_bessel_k", -7.50347, 2.22243, 354.234], - ["cyl_neumann", -7.50347, 2.22243, -3.59624], - ["sph_bessel", 0, 2.22243, 0.357761], - ["sph_neumann", 0, 2.22243, 0.272892], - ["cyl_bessel_i", 0.835801, 1.81454, 1.48687], - ["cyl_bessel_j", 0.835801, 1.81454, 0.599555], - ["cyl_bessel_k", 0.835801, 1.81454, 0.167517], - ["cyl_neumann", 0.835801, 1.81454, -0.103939], - ["sph_bessel", 1, 1.81454, 0.42774], - ["sph_neumann", 1, 1.81454, -0.461519], - ["cyl_bessel_i", -1, -8.35717, -560.474], - ["cyl_bessel_j", -1, -8.35717, 0.268956], - ["cyl_bessel_k", -0.10039, 8.35717, 0.000100382], - ["cyl_neumann", -0.10039, 8.35717, 0.273118], - ["sph_bessel", 6, 8.35717, 0.147167], - ["sph_neumann", 6, 8.35717, -0.00218726], - ["cyl_bessel_i", 8, -6.67288, 1.22706], - ["cyl_bessel_j", 8, -6.67288, 0.10095], - ["cyl_bessel_k", 8.50456, 6.67288, 0.0648458], - ["cyl_neumann", 8.50456, 6.67288, -0.931831], - ["sph_bessel", 4, 6.67288, 0.161166], - ["sph_neumann", 4, 6.67288, 0.0593303], - ["cyl_bessel_i", -8, -3.48179, 0.00291432], - ["cyl_bessel_j", -8, -3.48179, 0.00148539], - ["cyl_bessel_k", -7.1014, 3.48179, 5.28111], - ["cyl_neumann", -7.1014, 3.48179, 8.69768], - ["sph_bessel", 9, 3.48179, 8.57394e-05], - ["sph_neumann", 9, 3.48179, -189.725], - ["cyl_bessel_i", -1, -9.16822, -1209.58], - ["cyl_bessel_j", -1, -9.16822, 0.222404], - ["cyl_bessel_k", -0.328978, 9.16822, 4.28565e-05], - ["cyl_neumann", -0.328978, 9.16822, 0.133812], - ["sph_bessel", 9, 9.16822, 0.0752846], - ["sph_neumann", 9, 9.16822, -0.17498], - ["cyl_bessel_i", -4, -3.68293, 0.912407], - ["cyl_bessel_j", -4, -3.68293, 0.232636], - ["cyl_bessel_k", -3.62997, 3.68293, 0.0735086], - ["cyl_neumann", -3.62997, 3.68293, -0.467728], - ["sph_bessel", 5, 3.68293, 0.0379293], - ["sph_neumann", 5, 3.68293, -0.908662], - ["cyl_bessel_i", 6.11362, 7.53252, 22.5449], - ["cyl_bessel_j", 6.11362, 7.53252, 0.351615], - ["cyl_bessel_k", 6.11362, 7.53252, 0.00228427], - ["cyl_neumann", 6.11362, 7.53252, -0.101001], - ["sph_bessel", 5, 7.53252, 0.155321], - ["sph_neumann", 5, 7.53252, 0.0262202], - ["cyl_bessel_i", 4.18229, 5.20598, 5.69618], - ["cyl_bessel_j", 4.18229, 5.20598, 0.386537], - ["cyl_bessel_k", 4.18229, 5.20598, 0.0131229], - ["cyl_neumann", 4.18229, 5.20598, -0.186398], - ["sph_bessel", 9, 5.20598, 0.00220675], - ["sph_neumann", 9, 5.20598, -5.51105], - ["cyl_bessel_i", -6.85055, 0.503723, 983143], - ["cyl_bessel_j", -6.85055, 0.503723, 1.0047e+06], - ["cyl_bessel_k", -6.85055, 0.503723, 3.41324e+06], - ["cyl_neumann", -6.85055, 0.503723, 1.98028e+06], - ["sph_bessel", 10, 0.503723, 7.60749e-14], - ["sph_neumann", 10, 0.503723, -1.24409e+12], - ["cyl_bessel_i", 5.99273, 2.32385, 0.00418837], - ["cyl_bessel_j", 5.99273, 2.32385, 0.00284636], - ["cyl_bessel_k", 5.99273, 2.32385, 18.5485], - ["cyl_neumann", 5.99273, 2.32385, -20.3284], - ["sph_bessel", 9, 2.32385, 2.65254e-06], - ["sph_neumann", 9, 2.32385, -8809.56], - ["cyl_bessel_i", 2.54528, 5.31053, 18.5502], - ["cyl_bessel_j", 2.54528, 5.31053, 0.16231], - ["cyl_bessel_k", 2.54528, 5.31053, 0.00457722], - ["cyl_neumann", 2.54528, 5.31053, 0.329043], - ["sph_bessel", 2, 5.31053, 0.0791575], - ["sph_neumann", 2, 5.31053, 0.182664], - ["cyl_bessel_i", 7.54013, 2.83657, 0.00115315], - ["cyl_bessel_j", 7.54013, 2.83657, 0.000719823], - ["cyl_bessel_k", 7.54013, 2.83657, 53.7789], - ["cyl_neumann", 7.54013, 2.83657, -63.4366], - ["sph_bessel", 9, 2.83657, 1.49682e-05], - ["sph_neumann", 9, 2.83657, -1299.75], - ["cyl_bessel_i", 3.71167, 3.02275, 0.470382], - ["cyl_bessel_j", 3.71167, 3.02275, 0.177665], - ["cyl_bessel_k", 3.71167, 3.02275, 0.221126], - ["cyl_neumann", 3.71167, 3.02275, -0.770773], - ["sph_bessel", 9, 3.02275, 2.58322e-05], - ["sph_neumann", 9, 3.02275, -711.569], - ["cyl_bessel_i", -9.50312, 8.67655, 5.31574], - ["cyl_bessel_j", -9.50312, 8.67655, -0.517948], - ["cyl_bessel_k", -9.50312, 8.67655, 0.0072988], - ["cyl_neumann", -9.50312, 8.67655, -0.144548], - ["sph_bessel", 2, 8.67655, -0.0460811], - ["sph_neumann", 2, 8.67655, -0.108214], - ["cyl_bessel_i", -1, -7.62485, -280.716], - ["cyl_bessel_j", -1, -7.62485, 0.164887], - ["cyl_bessel_k", -0.0301369, 7.62485, 0.000218189], - ["cyl_neumann", -0.0301369, 7.62485, 0.159972], - ["sph_bessel", 7, 7.62485, 0.109295], - ["sph_neumann", 7, 7.62485, -0.168748], - ["cyl_bessel_i", 1.57277, 7.15062, 160.884], - ["cyl_bessel_j", 1.57277, 7.15062, -0.185673], - ["cyl_bessel_k", 1.57277, 7.15062, 0.000425206], - ["cyl_neumann", 1.57277, 7.15062, -0.237692], - ["sph_bessel", 6, 7.15062, 0.142706], - ["sph_neumann", 6, 7.15062, -0.129577], - ["cyl_bessel_i", -10, -8.93127, 4.74078], - ["cyl_bessel_j", -10, -8.93127, 0.119498], - ["cyl_bessel_k", -9.12714, 8.93127, 0.00357327], - ["cyl_neumann", -9.12714, 8.93127, 0.296753], - ["sph_bessel", 6, 8.93127, 0.123788], - ["sph_neumann", 6, 8.93127, 0.0491768], - ["cyl_bessel_i", 4, -0.171541, 2.25829e-06], - ["cyl_bessel_j", 4, -0.171541, 2.25166e-06], - ["cyl_bessel_k", 4.96692, 0.171541, 2.26371e+06], - ["cyl_neumann", 4.96692, 0.171541, -1.44648e+06], - ["sph_bessel", 2, 0.171541, 0.00195764], - ["sph_neumann", 2, 0.171541, -597.252], - ["cyl_bessel_i", -4, -0.603319, 0.000351356], - ["cyl_bessel_j", -4, -0.603319, 0.000338797], - ["cyl_bessel_k", -3.02084, 0.603319, 36.4334], - ["cyl_neumann", -3.02084, 0.603319, 25.3317], - ["sph_bessel", 2, 0.603319, 0.0236417], - ["sph_neumann", 2, 0.603319, -14.5606], - ["cyl_bessel_i", -7.53551, 8.00183, 12.7991], - ["cyl_bessel_j", -7.53551, 8.00183, -0.273256], - ["cyl_bessel_k", -7.53551, 8.00183, 0.00355087], - ["cyl_neumann", -7.53551, 8.00183, -0.304828], - ["sph_bessel", 4, 8.00183, 0.0206679], - ["sph_neumann", 4, 8.00183, 0.135086], - ["cyl_bessel_i", 9, -3.63952, -0.00083579], - ["cyl_bessel_j", 9, -3.63952, -0.000430825], - ["cyl_bessel_k", 9.08811, 3.63952, 70.8721], - ["cyl_neumann", 9.08811, 3.63952, -102.55], - ["sph_bessel", 10, 3.63952, 2.21627e-05], - ["sph_neumann", 10, 3.63952, -629.909], - ["cyl_bessel_i", -2.98486, 8.23219, 300.276], - ["cyl_bessel_j", -2.98486, 8.23219, 0.286154], - ["cyl_bessel_k", -2.98486, 8.23219, 0.000190268], - ["cyl_neumann", -2.98486, 8.23219, 0.0276635], - ["sph_bessel", 5, 8.23219, 0.108119], - ["sph_neumann", 5, 8.23219, 0.0878742], - ["cyl_bessel_i", 3, -9.18751, -780.476], - ["cyl_bessel_j", 3, -9.18751, 0.140255], - ["cyl_bessel_k", 3.51304, 9.18751, 7.86307e-05], - ["cyl_neumann", 3.51304, 9.18751, -0.107435], - ["sph_bessel", 7, 9.18751, 0.136689], - ["sph_neumann", 7, 9.18751, -0.0234403], - ["cyl_bessel_i", -7, -3.50398, -0.01464], - ["cyl_bessel_j", -7, -3.50398, 0.00679068], - ["cyl_bessel_k", -6.50483, 3.50398, 2.22984], - ["cyl_neumann", -6.50483, 3.50398, 0.0801367], - ["sph_bessel", 8, 3.50398, 0.00047492], - ["sph_neumann", 8, 3.50398, -38.8885], - ["cyl_bessel_i", 0, -0.0553816, 1.00077], - ["cyl_bessel_j", 0, -0.0553816, 0.999233], - ["cyl_bessel_k", 0.721373, 0.0553816, 8.26596], - ["cyl_neumann", 0.721373, 0.0553816, -5.40892], - ["sph_bessel", 4, 0.0553816, 9.95335e-09], - ["sph_neumann", 4, 0.0553816, -2.01585e+08], - ["cyl_bessel_i", 2.74527, 2.24474, 0.432128], - ["cyl_bessel_j", 2.74527, 2.24474, 0.220114], - ["cyl_bessel_k", 2.74527, 2.24474, 0.323844], - ["cyl_neumann", 2.74527, 2.24474, -0.790245], - ["sph_bessel", 7, 2.24474, 0.000122019], - ["sph_neumann", 7, 2.24474, -255.379], - ["cyl_bessel_i", -5, -9.57989, -493.19], - ["cyl_bessel_j", -5, -9.57989, -0.175594], - ["cyl_bessel_k", -4.42218, 9.57989, 7.21386e-05], - ["cyl_neumann", -4.42218, 9.57989, -0.237152], - ["sph_bessel", 7, 9.57989, 0.129064], - ["sph_neumann", 7, 9.57989, 0.0101783], - ["cyl_bessel_i", -8.31407, 6.48532, 0.690493], - ["cyl_bessel_j", -8.31407, 6.48532, 0.827459], - ["cyl_bessel_k", -8.31407, 6.48532, 0.0726749], - ["cyl_neumann", -8.31407, 6.48532, -0.46665], - ["sph_bessel", 2, 6.48532, -0.0986238], - ["sph_neumann", 2, 6.48532, 0.125961], - ["cyl_bessel_i", -9, -1.31369, -6.54795e-08], - ["cyl_bessel_j", -9, -1.31369, 6.00662e-08], - ["cyl_bessel_k", -8.08732, 1.31369, 84719.1], - ["cyl_neumann", -8.08732, 1.31369, -58639.9], - ["sph_bessel", 9, 1.31369, 1.70804e-08], - ["sph_neumann", 9, 1.31369, -2.36863e+06], - ["cyl_bessel_i", -7.93764, 0.225615, -9.1515e+09], - ["cyl_bessel_j", -7.93764, 0.225615, -9.18514e+09], - ["cyl_bessel_k", -7.93764, 0.225615, 7.38453e+10], - ["cyl_neumann", -7.93764, 0.225615, -4.62815e+10], - ["sph_bessel", 1, 0.225615, 0.0748229], - ["sph_neumann", 1, 0.225615, -20.1392], - ["cyl_bessel_i", 3, -7.98514, -232.549], - ["cyl_bessel_j", 3, -7.98514, 0.291048], - ["cyl_bessel_k", 3.88922, 7.98514, 0.000359339], - ["cyl_neumann", 3.88922, 7.98514, 0.26957], - ["sph_bessel", 8, 7.98514, 0.0755992], - ["sph_neumann", 8, 7.98514, -0.211928], - ["cyl_bessel_i", 4, -6.31303, 23.7474], - ["cyl_bessel_j", 4, -6.31303, 0.31048], - ["cyl_bessel_k", 4.03783, 6.31303, 0.00287623], - ["cyl_neumann", 4.03783, 6.31303, 0.164831], - ["sph_bessel", 2, 6.31303, -0.0796118], - ["sph_neumann", 2, 6.31303, 0.144167], - ["cyl_bessel_i", -0.861386, 1.31593, 1.00966], - ["cyl_bessel_j", -0.861386, 1.31593, -0.332739], - ["cyl_bessel_k", -0.861386, 1.31593, 0.337834], - ["cyl_neumann", -0.861386, 1.31593, 0.650858], - ["sph_bessel", 9, 1.31593, 1.7342e-08], - ["sph_neumann", 9, 1.31593, -2.329e+06], - ["cyl_bessel_i", -6, -6.07757, 3.73205], - ["cyl_bessel_j", -6, -6.07757, 0.25479], - ["cyl_bessel_k", -5.12254, 6.07757, 0.00789359], - ["cyl_neumann", -5.12254, 6.07757, 0.0599454], - ["sph_bessel", 2, 6.07757, -0.0486437], - ["sph_neumann", 2, 6.07757, 0.164574], - ["cyl_bessel_i", -9.5789, 9.68195, 20.6139], - ["cyl_bessel_j", -9.5789, 9.68195, -0.2836], - ["cyl_bessel_k", -9.5789, 9.68195, 0.00177993], - ["cyl_neumann", -9.5789, 9.68195, -0.298044], - ["sph_bessel", 6, 9.68195, 0.0713991], - ["sph_neumann", 6, 9.68195, 0.095153], - ["cyl_bessel_i", 6.50983, 0.124883, 7.55974e-12], - ["cyl_bessel_j", 6.50983, 0.124883, 7.5519e-12], - ["cyl_bessel_k", 6.50983, 0.124883, 1.01581e+10], - ["cyl_neumann", 6.50983, 0.124883, -6.47599e+09], - ["sph_bessel", 3, 0.124883, 1.85328e-05], - ["sph_neumann", 3, 0.124883, -61767.6], - ["beta", 5.43738, 1.71319, 0.0451108], - ["beta", 2.89448, 0.0497214, 18.7339], - ["beta", 7.46809, 6.23994, 0.00010934], - ["beta", 5.22812, 3.45574, 0.00522637], - ["beta", 6.36728, 2.03572, 0.0201107], - ["beta", 4.31352, 1.88203, 0.051268], - ["beta", 7.08725, 9.90967, 1.21142e-05], - ["beta", 5.32322, 8.74347, 0.000124601], - ["beta", 9.34825, 9.87443, 1.90788e-06], - ["beta", 7.24796, 2.49304, 0.00749075], - ["beta", 9.83016, 2.51868, 0.00354993], - ["beta", 8.44675, 4.53855, 0.00033414], - ["beta", 8.9874, 6.37067, 3.93316e-05], - ["beta", 7.92248, 5.69563, 0.000134021], - ["beta", 0.8492, 9.99829, 0.158563], - ["beta", 7.75038, 7.31423, 3.85812e-05], - ["beta", 1.42852, 5.46504, 0.0742643], - ["beta", 8.88054, 9.47825, 3.56474e-06], - ["beta", 9.06027, 4.52497, 0.000259517], - ["beta", 5.47452, 6.58204, 0.000365749], - ["beta", 8.24053, 3.51883, 0.00125396], - ["beta", 0.189918, 3.70955, 3.86156], - ["beta", 0.00782859, 6.02956, 125.474], - ["beta", 7.49258, 2.01902, 0.0151955], - ["beta", 2.57324, 6.21319, 0.00949151], - ["beta", 1.01981, 2.19734, 0.441227], - ["beta", 9.71832, 2.07482, 0.00828162], - ["beta", 3.4171, 7.13227, 0.00220841], - ["beta", 7.20966, 4.86089, 0.000439923], - ["beta", 5.39944, 6.61502, 0.000381674], - ["beta", 7.34528, 7.90898, 3.37583e-05], - ["beta", 6.71504, 4.85612, 0.00058301], - ["beta", 4.56017, 5.37249, 0.00173169], - ["beta", 5.87835, 8.49994, 8.17672e-05], - ["beta", 6.38919, 6.37431, 0.000205797], - ["beta", 6.08356, 2.01189, 0.0227678], - ["beta", 4.40998, 7.34242, 0.000648347], - ["beta", 9.75145, 7.56476, 8.6738e-06], - ["beta", 7.94025, 6.06033, 9.53499e-05], - ["beta", 5.61042, 9.205, 7.3666e-05], - ["beta", 8.68901, 0.569803, 0.462354], - ["beta", 9.29875, 3.9614, 0.000474023], - ["beta", 4.27731, 4.60095, 0.0037018], - ["beta", 9.71905, 8.49655, 4.08561e-06], - ["beta", 6.42907, 5.29782, 0.000468284], - ["beta", 7.96906, 7.14175, 3.79639e-05], - ["beta", 5.65342, 7.53013, 0.00017481], - ["beta", 4.68445, 6.19567, 0.00092629], - ["beta", 3.70331, 5.39251, 0.0037256], - ["beta", 9.94457, 1.04385, 0.0885876], - ["beta", 7.58347, 1.07694, 0.107863], - ["beta", 3.64423, 6.47693, 0.0022638], - ["beta", 4.2543, 9.6481, 0.00028521], - ["beta", 9.87066, 8.96982, 2.55068e-06], - ["beta", 6.57817, 4.91419, 0.000598654], - ["beta", 8.7025, 2.23292, 0.00771546], - ["beta", 5.80084, 9.36054, 5.60965e-05], - ["beta", 0.481414, 5.59908, 0.820973], - ["beta", 5.43028, 7.71843, 0.000192619], - ["beta", 7.10064, 1.42663, 0.0519003], - ["beta", 2.53228, 9.33181, 0.00391778], - ["beta", 9.33454, 2.20476, 0.00701603], - ["beta", 8.40432, 7.61149, 1.96092e-05], - ["beta", 0.904159, 0.402794, 2.61726], - ["beta", 7.75319, 9.4034, 9.14529e-06], - ["beta", 2.74711, 5.19757, 0.0115493], - ["beta", 9.56415, 2.02418, 0.00943596], - ["beta", 9.44011, 0.612901, 0.373523], - ["beta", 2.54554, 0.201872, 3.88965], - ["beta", 0.852063, 9.0165, 0.171701], - ["beta", 9.82615, 1.6511, 0.0196327], - ["beta", 2.02192, 2.24728, 0.134364], - ["beta", 1.69071, 6.3591, 0.0364494], - ["beta", 4.53191, 2.19808, 0.0306486], - ["beta", 7.00224, 1.93562, 0.0199561], - ["beta", 5.75182, 4.99803, 0.000935619], - ["beta", 0.322443, 7.15128, 1.4936], - ["beta", 2.00733, 4.0057, 0.0494057], - ["beta", 8.47945, 6.73179, 3.83568e-05], - ["beta", 1.48589, 9.13783, 0.0318485], - ["beta", 7.08407, 3.65468, 0.00169417], - ["beta", 7.70133, 4.12746, 0.000745045], - ["beta", 1.44993, 9.74869, 0.0315709], - ["beta", 3.24803, 2.9477, 0.0288503], - ["beta", 3.58225, 2.59873, 0.0317478], - ["beta", 5.35169, 1.53762, 0.062626], - ["beta", 2.92817, 6.12332, 0.0061714], - ["beta", 7.91203, 8.74139, 1.23663e-05], - ["beta", 8.30012, 8.84477, 8.55546e-06], - ["beta", 0.600091, 2.38175, 0.929292], - ["beta", 0.253569, 5.78954, 2.32641], - ["beta", 0.117011, 3.06178, 7.20817], - ["beta", 4.3661, 8.69075, 0.000366092], - ["beta", 2.19768, 1.77675, 0.175246], - ["beta", 0.239327, 2.98162, 3.01619], - ["beta", 5.17838, 8.93513, 0.000132104], - ["beta", 0.874823, 6.05102, 0.227633], - ["beta", 1.04186, 0.887291, 1.08512], - ["beta", 5.76291, 9.33735, 5.89872e-05], - ["beta", 1.26049, 4.60205, 0.127642], - ["ellint_1", -0.984468, 0.295747, 0.300014], - ["ellint_2", -0.984468, 0.295747, 0.291589], - ["ellint_3", -0.984468, 9.46851, 0.295747, 0.493196], - ["ellint_1", 0.838026, 0.144616, 0.144971], - ["ellint_2", 0.838026, 0.144616, 0.144263], - ["ellint_3", 0.838026, 15.4614, 0.144616, 0.164499], - ["ellint_1", 0.545513, -1.33552, -1.43283], - ["ellint_2", 0.545513, -1.33552, -1.2485], - ["ellint_3", 0.545513, 0.614444, -1.33552, -2.11035], - ["ellint_1", -0.101389, 1.10574, 1.10756], - ["ellint_2", -0.101389, 1.10574, 1.10393], - ["ellint_3", -0.101389, 1.13461, 1.10574, 2.54495], - ["ellint_1", -0.46228, -0.334716, -0.336035], - ["ellint_2", -0.46228, -0.334716, -0.333405], - ["ellint_3", -0.46228, 3.71831, -0.334716, -0.397609], - ["ellint_1", -0.87414, 0.353207, 0.35892], - ["ellint_2", -0.87414, 0.353207, 0.347655], - ["ellint_3", -0.87414, 6.2976, 0.353207, 0.555621], - ["ellint_1", 0.587268, 0.176722, 0.177038], - ["ellint_2", 0.587268, 0.176722, 0.176406], - ["ellint_3", 0.587268, 7.15596, 0.176722, 0.192244], - ["ellint_1", -0.477195, -0.945677, -0.974616], - ["ellint_2", -0.477195, -0.945677, -0.918177], - ["ellint_3", -0.477195, 0.302658, -0.945677, -1.06091], - ["ellint_1", 0.0680548, 1.09223, 1.09303], - ["ellint_2", 0.0680548, 1.09223, 1.09144], - ["ellint_3", 0.0680548, 0.31128, 1.09223, 1.22052], - ["ellint_1", 0.347204, 0.825219, 0.835382], - ["ellint_2", 0.347204, 0.825219, 0.815267], - ["ellint_3", 0.347204, 1.41402, 0.825219, 1.361], - ["ellint_1", 0.6392, -0.709607, -0.733586], - ["ellint_2", 0.6392, -0.709607, -0.68698], - ["ellint_3", 0.6392, 2.0131, -0.709607, -1.36893], - ["ellint_1", -0.848038, 1.23319, 1.49455], - ["ellint_2", -0.848038, 1.23319, 1.04305], - ["ellint_3", -0.848038, 0.740237, 1.23319, 2.4358], - ["ellint_1", 0.0444439, -0.266119, -0.266126], - ["ellint_2", 0.0444439, -0.266119, -0.266113], - ["ellint_3", 0.0444439, 12.7919, -0.266119, -0.496551], - ["ellint_1", 0.261943, 1.06557, 1.07687], - ["ellint_2", 0.261943, 1.06557, 1.05446], - ["ellint_3", 0.261943, 0.352215, 1.06557, 1.21738], - ["ellint_1", 0.697384, -0.255215, -0.256563], - ["ellint_2", 0.697384, -0.255215, -0.253878], - ["ellint_3", 0.697384, 10.5985, -0.255215, -0.364698], - ["ellint_1", -0.169898, -1.47118, -1.48124], - ["ellint_2", -0.169898, -1.47118, -1.46122], - ["ellint_3", -0.169898, 0.891215, -1.47118, -3.90997], - ["ellint_1", -0.345543, 0.217188, 0.21739], - ["ellint_2", -0.345543, 0.217188, 0.216986], - ["ellint_3", -0.345543, 9.74104, 0.217188, 0.263935], - ["ellint_1", -0.666716, -0.826831, -0.868204], - ["ellint_2", -0.666716, -0.826831, -0.788805], - ["ellint_3", -0.666716, 1.33096, -0.826831, -1.36078], - ["ellint_1", 0.345407, 0.791023, 0.799959], - ["ellint_2", 0.345407, 0.791023, 0.782258], - ["ellint_3", 0.345407, 1.78301, 0.791023, 1.66329], - ["ellint_1", -0.424951, -0.333977, -0.335083], - ["ellint_2", -0.424951, -0.333977, -0.332877], - ["ellint_3", -0.424951, 1.46922, -0.333977, -0.354965], - ["ellint_1", 0.455995, 0.91142, 0.93512], - ["ellint_2", 0.455995, 0.91142, 0.888731], - ["ellint_3", 0.455995, 0.306343, 0.91142, 1.01321], - ["ellint_1", -0.209138, 0.309056, 0.309267], - ["ellint_2", -0.209138, 0.309056, 0.308844], - ["ellint_3", -0.209138, 7.61937, 0.309056, 0.451785], - ["ellint_1", 0.530719, 0.313064, 0.314494], - ["ellint_2", 0.530719, 0.313064, 0.311646], - ["ellint_3", 0.530719, 0.188901, 0.313064, 0.316425], - ["ellint_1", -0.0481149, -0.497058, -0.497103], - ["ellint_2", -0.0481149, -0.497058, -0.497013], - ["ellint_3", -0.0481149, 2.97598, -0.497058, -0.713138], - ["ellint_1", -0.0445318, 1.32618, 1.32672], - ["ellint_2", -0.0445318, 1.32618, 1.32564], - ["ellint_3", -0.0445318, 0.980876, 1.32618, 3.66074], - ["ellint_1", -0.955478, -1.09603, -1.36441], - ["ellint_2", -0.955478, -1.09603, -0.911687], - ["ellint_3", -0.955478, 1.19138, -1.09603, -4.25377], - ["ellint_1", 0.0239343, -1.10623, -1.10633], - ["ellint_2", 0.0239343, -1.10623, -1.10613], - ["ellint_3", 0.0239343, 1.08475, -1.10623, -2.28057], - ["ellint_1", 0.35651, -0.346231, -0.347095], - ["ellint_2", 0.35651, -0.346231, -0.34537], - ["ellint_3", 0.35651, 3.86336, -0.346231, -0.420596], - ["ellint_1", -0.78602, -0.523364, -0.538426], - ["ellint_2", -0.78602, -0.523364, -0.509041], - ["ellint_3", -0.78602, 3.3039, -0.523364, -0.932434], - ["ellint_1", -0.588546, -0.793881, -0.821694], - ["ellint_2", -0.588546, -0.793881, -0.767676], - ["ellint_3", -0.588546, 0.597188, -0.793881, -0.937944], - ["ellint_1", -0.209187, 1.01376, 1.02004], - ["ellint_2", -0.209187, 1.01376, 1.00755], - ["ellint_3", -0.209187, 0.852227, 1.01376, 1.44958], - ["ellint_1", 0.072815, -1.40598, -1.40763], - ["ellint_2", 0.072815, -1.40598, -1.40433], - ["ellint_3", 0.072815, 0.551379, -1.40598, -1.98458], - ["ellint_1", -0.458443, 0.286873, 0.287692], - ["ellint_2", -0.458443, 0.286873, 0.286057], - ["ellint_3", -0.458443, 10.1671, 0.286873, 0.476763], - ["ellint_1", -0.574771, -0.104067, -0.104129], - ["ellint_2", -0.574771, -0.104067, -0.104005], - ["ellint_3", -0.574771, 87.0271, -0.104067, -0.223546], - ["ellint_1", 0.864387, 1.34285, 1.70889], - ["ellint_2", 0.864387, 1.34285, 1.09538], - ["ellint_3", 0.864387, 0.0473684, 1.34285, 1.74912], - ["ellint_1", -0.343869, -0.280505, -0.280935], - ["ellint_2", -0.343869, -0.280505, -0.280077], - ["ellint_3", -0.343869, 8.78366, -0.280505, -0.398367], - ["ellint_1", -0.692352, 0.156082, 0.156386], - ["ellint_2", -0.692352, 0.156082, 0.155779], - ["ellint_3", -0.692352, 34.1786, 0.156082, 0.262384], - ["ellint_1", -0.683543, 1.27797, 1.43087], - ["ellint_2", -0.683543, 1.27797, 1.15062], - ["ellint_3", -0.683543, 0.752585, 1.27797, 2.39059], - ["ellint_1", 0.338052, -1.337, -1.37067], - ["ellint_2", 0.338052, -1.337, -1.30462], - ["ellint_3", 0.338052, 0.714809, -1.337, -2.22571], - ["ellint_1", -0.406244, -1.09029, -1.1203], - ["ellint_2", -0.406244, -1.09029, -1.06159], - ["ellint_3", -0.406244, 0.368515, -1.09029, -1.28352], - ["ellint_1", -0.0428997, 1.05212, 1.05241], - ["ellint_2", -0.0428997, 1.05212, 1.05184], - ["ellint_3", -0.0428997, 1.16408, 1.05212, 2.18933], - ["ellint_1", 0.9268, 0.43004, 0.441831], - ["ellint_2", 0.9268, 0.43004, 0.418806], - ["ellint_3", 0.9268, 1.2522, 0.43004, 0.48072], - ["ellint_1", 0.708416, 0.685444, 0.712568], - ["ellint_2", 0.708416, 0.685444, 0.660105], - ["ellint_3", 0.708416, 2.12802, 0.685444, 1.32437], - ["ellint_1", -0.0241848, -0.832604, -0.832653], - ["ellint_2", -0.0241848, -0.832604, -0.832555], - ["ellint_3", -0.0241848, 0.600834, -0.832604, -0.960801], - ["ellint_1", -0.378848, -1.18504, -1.21705], - ["ellint_2", -0.378848, -1.18504, -1.15438], - ["ellint_3", -0.378848, 0.33314, -1.18504, -1.39835], - ["ellint_1", 0.353249, 1.47103, 1.51695], - ["ellint_2", 0.353249, 1.47103, 1.42722], - ["ellint_3", 0.353249, 0.514756, 1.47103, 2.12571], - ["ellint_1", -0.567713, -1.2609, -1.35348], - ["ellint_2", -0.567713, -1.2609, -1.17832], - ["ellint_3", -0.567713, 0.189859, -1.2609, -1.47081], - ["ellint_1", 0.528307, -0.924118, -0.957992], - ["ellint_2", 0.528307, -0.924118, -0.892254], - ["ellint_3", 0.528307, 0.566041, -0.924118, -1.13382], - ["ellint_1", -0.600292, 0.133885, 0.134029], - ["ellint_2", -0.600292, 0.133885, 0.133741], - ["ellint_3", -0.600292, 22.1983, 0.133885, 0.157709], - ["ellint_1", -0.66083, -0.0102686, -0.0102686], - ["ellint_2", -0.66083, -0.0102686, -0.0102685], - ["ellint_3", -0.66083, 3893.99, -0.0102686, -0.012171], - ["ellint_1", 0.3211, 1.56607, 1.60883], - ["ellint_2", 0.3211, 1.56607, 1.52501], - ["ellint_3", 0.3211, 0.436156, 1.56607, 2.14868], - ["ellint_1", 0.172887, 0.642177, 0.643398], - ["ellint_2", 0.172887, 0.642177, 0.64096], - ["ellint_3", 0.172887, 0.885503, 0.642177, 0.734085], - ["ellint_1", 0.841379, -0.757802, -0.812603], - ["ellint_2", 0.841379, -0.757802, -0.709311], - ["ellint_3", 0.841379, 2.06607, -0.757802, -2.46395], - ["ellint_1", -0.923881, 0.775936, 0.850552], - ["ellint_2", -0.923881, 0.775936, 0.712442], - ["ellint_3", -0.923881, 0.609328, 0.775936, 0.97359], - ["ellint_1", 0.454701, 0.539973, 0.545223], - ["ellint_2", 0.454701, 0.539973, 0.534812], - ["ellint_3", 0.454701, 1.78819, 0.539973, 0.675698], - ["ellint_1", -0.356787, -0.877363, -0.8901], - ["ellint_2", -0.356787, -0.877363, -0.864936], - ["ellint_3", -0.356787, 0.693058, -0.877363, -1.0788], - ["ellint_1", -0.32632, -0.934312, -0.946876], - ["ellint_2", -0.32632, -0.934312, -0.922027], - ["ellint_3", -0.32632, 1.00688, -0.934312, -1.38203], - ["ellint_1", 0.064671, 0.293766, 0.293783], - ["ellint_2", 0.064671, 0.293766, 0.293748], - ["ellint_3", 0.064671, 2.40198, 0.293766, 0.316574], - ["ellint_1", 0.266846, -0.411852, -0.412657], - ["ellint_2", 0.266846, -0.411852, -0.411049], - ["ellint_3", 0.266846, 3.73669, -0.411852, -0.553346], - ["ellint_1", -0.145555, 0.235233, 0.235279], - ["ellint_2", -0.145555, 0.235233, 0.235188], - ["ellint_3", -0.145555, 11.8295, 0.235233, 0.324624], - ["ellint_1", -0.32953, 0.394782, 0.395869], - ["ellint_2", -0.32953, 0.394782, 0.3937], - ["ellint_3", -0.32953, 6.08534, 0.394782, 0.772534], - ["ellint_1", 0.692478, 0.214558, 0.215348], - ["ellint_2", 0.692478, 0.214558, 0.213773], - ["ellint_3", 0.692478, 7.36228, 0.214558, 0.245962], - ["ellint_1", 0.208947, -0.257717, -0.25784], - ["ellint_2", 0.208947, -0.257717, -0.257594], - ["ellint_3", 0.208947, 0.450186, -0.257717, -0.260422], - ["ellint_1", -0.361696, -1.51208, -1.56336], - ["ellint_2", -0.361696, -1.51208, -1.46335], - ["ellint_3", -0.361696, 0.0898474, -1.51208, -1.63695], - ["ellint_1", -0.169185, -1.44398, -1.45356], - ["ellint_2", -0.169185, -1.44398, -1.4345], - ["ellint_3", -0.169185, 0.623731, -1.44398, -2.24493], - ["ellint_1", 0.8723, -0.0660934, -0.06613], - ["ellint_2", 0.8723, -0.0660934, -0.0660568], - ["ellint_3", 0.8723, 45.3058, -0.0660934, -0.0710945], - ["ellint_1", 0.302987, 1.38791, 1.41703], - ["ellint_2", 0.302987, 1.38791, 1.35971], - ["ellint_3", 0.302987, 0.683318, 1.38791, 2.28648], - ["ellint_1", -0.550584, -0.457521, -0.462291], - ["ellint_2", -0.550584, -0.457521, -0.452838], - ["ellint_3", -0.550584, 0.792576, -0.457521, -0.48963], - ["ellint_1", -0.983507, -0.537127, -0.563947], - ["ellint_2", -0.983507, -0.537127, -0.512541], - ["ellint_3", -0.983507, 1.56132, -0.537127, -0.677294], - ["ellint_1", -0.0452787, 1.39888, 1.39951], - ["ellint_2", -0.0452787, 1.39888, 1.39825], - ["ellint_3", -0.0452787, 0.703708, 1.39888, 2.31983], - ["ellint_1", -0.868191, 1.05349, 1.22341], - ["ellint_2", -0.868191, 1.05349, 0.921796], - ["ellint_3", -0.868191, 1.26759, 1.05349, 3.85575], - ["ellint_1", -0.60511, 0.97011, 1.02277], - ["ellint_2", -0.60511, 0.97011, 0.921957], - ["ellint_3", -0.60511, 0.954422, 0.97011, 1.51374], - ["ellint_1", 0.246655, 1.17235, 1.18507], - ["ellint_2", 0.246655, 1.17235, 1.15985], - ["ellint_3", 0.246655, 0.132714, 1.17235, 1.2446], - ["ellint_1", 0.0108285, 1.20277, 1.20279], - ["ellint_2", 0.0108285, 1.20277, 1.20274], - ["ellint_3", 0.0108285, 0.546037, 1.20277, 1.55992], - ["ellint_1", -0.321756, 1.03162, 1.04751], - ["ellint_2", -0.321756, 1.03162, 1.01613], - ["ellint_3", -0.321756, 1.30547, 1.03162, 2.99911], - ["ellint_1", -0.588025, -0.816919, -0.847078], - ["ellint_2", -0.588025, -0.816919, -0.788588], - ["ellint_3", -0.588025, 0.111995, -0.816919, -0.86677], - ["ellint_1", -0.654467, 0.622566, 0.639679], - ["ellint_2", -0.654467, 0.622566, 0.60625], - ["ellint_3", -0.654467, 2.91406, 0.622566, 2.16111], - ["ellint_1", -0.352998, 0.292698, 0.293213], - ["ellint_2", -0.352998, 0.292698, 0.292186], - ["ellint_3", -0.352998, 11.2968, 0.292698, 0.638871], - ["ellint_1", 0.685451, 0.360093, 0.363754], - ["ellint_2", 0.685451, 0.360093, 0.356499], - ["ellint_3", 0.685451, 0.457362, 0.360093, 0.37107], - ["ellint_1", -0.362985, -1.4075, -1.45163], - ["ellint_2", -0.362985, -1.4075, -1.36544], - ["ellint_3", -0.362985, 0.221728, -1.4075, -1.6236], - ["ellint_1", 0.088819, -1.2442, -1.24606], - ["ellint_2", 0.088819, -1.2442, -1.24234], - ["ellint_3", 0.088819, 0.408524, -1.2442, -1.50552], - ["ellint_1", 0.429571, 0.7186, 0.729292], - ["ellint_2", 0.429571, 0.7186, 0.708178], - ["ellint_3", 0.429571, 2.00874, 0.7186, 1.39381], - ["ellint_1", 0.449173, 1.40165, 1.47142], - ["ellint_2", 0.449173, 1.40165, 1.33698], - ["ellint_3", 0.449173, 0.129547, 1.40165, 1.56634], - ["ellint_1", -0.146986, 0.23252, 0.232565], - ["ellint_2", -0.146986, 0.23252, 0.232475], - ["ellint_3", -0.146986, 6.27887, 0.23252, 0.265521], - ["ellint_1", 0.654824, 0.322014, 0.324398], - ["ellint_2", 0.654824, 0.322014, 0.319661], - ["ellint_3", 0.654824, 2.51581, 0.322014, 0.357383], - ["ellint_1", 0.664508, 0.469113, 0.4767], - ["ellint_2", 0.664508, 0.469113, 0.46174], - ["ellint_3", 0.664508, 2.24812, 0.469113, 0.585489], - ["ellint_1", -0.99102, 0.376992, 0.386076], - ["ellint_2", -0.99102, 0.376992, 0.368287], - ["ellint_3", -0.99102, 6.52945, 0.376992, 0.73545], - ["ellint_1", -0.594747, 0.484307, 0.490931], - ["ellint_2", -0.594747, 0.484307, 0.47784], - ["ellint_3", -0.594747, 3.64855, 0.484307, 0.80108], - ["ellint_1", 0.262888, 0.562882, 0.564828], - ["ellint_2", 0.262888, 0.562882, 0.560949], - ["ellint_3", 0.262888, 0.160547, 0.562882, 0.574101], - ["ellint_1", -0.720498, 1.2116, 1.3637], - ["ellint_2", -0.720498, 1.2116, 1.08634], - ["ellint_3", -0.720498, 0.434823, 1.2116, 1.68359], - ["ellint_1", 0.184134, 0.916918, 0.920635], - ["ellint_2", 0.184134, 0.916918, 0.913225], - ["ellint_3", 0.184134, 1.14477, 0.916918, 1.43915], - ["ellint_1", -0.924615, 0.111955, 0.112156], - ["ellint_2", -0.924615, 0.111955, 0.111755], - ["ellint_3", -0.924615, 35.2911, 0.111955, 0.135168], - ["ellint_1", -0.436881, 0.304278, 0.305165], - ["ellint_2", -0.436881, 0.304278, 0.303396], - ["ellint_3", -0.436881, 8.66038, 0.304278, 0.482354], - ["ellint_1", 0.577638, 0.50128, 0.508187], - ["ellint_2", 0.577638, 0.50128, 0.494538], - ["ellint_3", 0.577638, 1.39343, 0.50128, 0.579911], - ["ellint_1", -0.168812, 0.922179, 0.925347], - ["ellint_2", -0.168812, 0.922179, 0.91903], - ["ellint_3", -0.168812, 0.650574, 0.922179, 1.12482], - ["ellint_1", -0.650175, 1.49605, 1.69531], - ["ellint_2", -0.650175, 1.49605, 1.33175], - ["ellint_3", -0.650175, 0.687165, 1.49605, 3.02154], - ["ellint_1", 0.487261, 0.838223, 0.859825], - ["ellint_2", 0.487261, 0.838223, 0.817544], - ["ellint_3", 0.487261, 0.910365, 0.838223, 1.10599], - ["ellint_1", -0.385032, -0.228967, -0.229261], - ["ellint_2", -0.385032, -0.228967, -0.228673], - ["ellint_3", -0.385032, 17.1196, -0.228967, -0.424836], - ["ellint_1", 0.0401356, -0.560297, -0.560342], - ["ellint_2", 0.0401356, -0.560297, -0.560253], - ["ellint_3", 0.0401356, 0.262997, -0.560297, -0.575519], - ["ellint_1", -0.58318, -0.365545, -0.368295], - ["ellint_2", -0.58318, -0.365545, -0.362831], - ["ellint_3", -0.58318, 6.80767, -0.365545, -0.673598], - ["expint", 6.42081, 119.909], - ["expint", 7.29916, 244.946], - ["expint", -6.16651, -0.000297553], - ["expint", 5.34783, 52.0993], - ["expint", -4.35434, -0.00246704], - ["expint", -5.46984, -0.00066374], - ["expint", 8.39989, 618.86], - ["expint", -4.16127, -0.0031104], - ["expint", 5.46797, 57.0589], - ["expint", -5.09274, -0.00103001], - ["expint", -6.30229, -0.000254806], - ["expint", 3.02352, 10.0926], - ["expint", -4.89292, -0.0013023], - ["expint", -1.95257, -0.0522275], - ["expint", -7.97003, -3.89437e-05], - ["expint", -2.16842, -0.038819], - ["expint", 9.70953, 1929.15], - ["expint", 9.66245, 1850.94], - ["expint", -8.5487, -2.04865e-05], - ["expint", -9.47408, -7.39196e-06], - ["expint", 0.636429, 0.879243], - ["expint", 3.13162, 10.8552], - ["expint", -6.16569, -0.000297832], - ["expint", 2.71408, 8.18828], - ["expint", 7.21006, 227.567], - ["expint", 8.51513, 683.072], - ["expint", -4.91741, -0.0012653], - ["expint", 0.756737, 1.22633], - ["expint", 5.35794, 52.4982], - ["expint", 0.879612, 1.56702], - ["expint", -5.64625, -0.000541118], - ["expint", -5.93221, -0.000389226], - ["expint", 8.58423, 724.821], - ["expint", 7.64758, 327.343], - ["expint", 0.87062, 1.54237], - ["expint", 2.70635, 8.14541], - ["expint", 5.18295, 46.0347], - ["expint", 2.286, 6.0939], - ["expint", -3.34795, -0.00841951], - ["expint", 1.24832, 2.57635], - ["expint", 8.80597, 877.409], - ["expint", 0.536002, 0.570919], - ["expint", 7.61674, 319.004], - ["expint", -2.32002, -0.0316419], - ["expint", -5.4647, -0.000667709], - ["expint", -2.33373, -0.0310671], - ["expint", 8.82282, 890.272], - ["expint", -0.995415, -0.221079], - ["expint", -7.81578, -4.62501e-05], - ["expint", -6.65382, -0.000170828], - ["expint", -8.04988, -3.56315e-05], - ["expint", -8.01814, -3.69127e-05], - ["expint", -2.60365, -0.0217462], - ["expint", -3.73007, -0.00525066], - ["expint", 1.67715, 3.84775], - ["expint", 6.14644, 96.4634], - ["expint", -1.21068, -0.155753], - ["expint", 2.21571, 5.79732], - ["expint", -9.29547, -8.99315e-06], - ["expint", 5.66591, 66.3726], - ["expint", -2.46589, -0.0260621], - ["expint", -7.71188, -5.19385e-05], - ["expint", 1.02303, 1.95772], - ["expint", -5.33049, -0.000780403], - ["expint", 9.39134, 1459.41], - ["expint", -8.62532, -1.88218e-05], - ["expint", -9.03558, -1.1969e-05], - ["expint", 7.42167, 271.132], - ["expint", 4.98729, 39.81], - ["expint", -5.6136, -0.000561933], - ["expint", 4.01807, 19.8791], - ["expint", -4.47311, -0.00214089], - ["expint", 3.9668, 19.1833], - ["expint", 3.40354, 13.0434], - ["expint", -8.12399, -3.28125e-05], - ["expint", 1.42712, 3.08607], - ["expint", 3.78362, 16.9033], - ["expint", 2.29628, 6.13829], - ["expint", -4.29467, -0.00264978], - ["expint", -8.68338, -1.76518e-05], - ["expint", -3.98148, -0.00386512], - ["expint", -2.69247, -0.0193704], - ["expint", 1.48985, 3.27103], - ["expint", -7.68035, -5.38012e-05], - ["expint", -2.8383, -0.0160447], - ["expint", -3.47816, -0.00716122], - ["expint", -5.49697, -0.000643179], - ["expint", -8.29695, -2.70779e-05], - ["expint", 0.147757, -1.18157], - ["expint", 0.192795, -0.866409], - ["expint", -1.71198, -0.073379], - ["expint", 3.66991, 15.6353], - ["expint", -1.57235, -0.0898777], - ["expint", 9.81442, 2115.75], - ["expint", 0.306404, -0.274066], - ["expint", -2.04623, -0.0458783], - ["expint", 9.47317, 1567.75], - ["expint", 6.41657, 119.504], - ["expint", 1.96594, 4.82947], - ["expint", 4.8351, 35.599], - ["hermite", 7, -2.87502, -18842], - ["hermite", 6, -5.7792, 1.87293e+06], - ["hermite", 8, 5.73186, 1.85235e+08], - ["hermite", 8, 8.58706, 6.20341e+09], - ["hermite", 3, -5.20605, -1066.32], - ["hermite", 0, -7.55584, 1], - ["hermite", 5, 9.69993, 2.60298e+06], - ["hermite", 2, -6.64268, 174.501], - ["hermite", 9, 7.28107, 2.04074e+10], - ["hermite", 0, -3.12747, 1], - ["hermite", 6, 2.78716, 6509.18], - ["hermite", 3, 6.78207, 2414.22], - ["hermite", 1, -4.14027, -8.28054], - ["hermite", 4, 1.62221, -3.5129], - ["hermite", 10, -1.44516, -85818.9], - ["hermite", 8, 7.37135, 1.69558e+09], - ["hermite", 7, -1.13316, -781.245], - ["hermite", 7, 0.600943, -382.107], - ["hermite", 7, -9.9307, -1.09265e+09], - ["hermite", 8, -6.77008, 8.12298e+08], - ["hermite", 8, -8.95559, 8.82881e+09], - ["hermite", 5, 2.94212, 3332.56], - ["hermite", 6, 4.78752, 534846], - ["hermite", 4, -4.09829, 3719.49], - ["hermite", 4, 5.1752, 10203.4], - ["hermite", 9, 9.96753, 4.11825e+11], - ["hermite", 6, 8.19934, 1.73258e+07], - ["hermite", 3, -3.80541, -395.19], - ["hermite", 0, 4.2125, 1], - ["hermite", 1, 9.16103, 18.3221], - ["hermite", 1, -2.81023, -5.62046], - ["hermite", 2, 0.646366, -0.328846], - ["hermite", 3, 9.85378, 7535.94], - ["hermite", 2, -2.14577, 16.4172], - ["hermite", 5, 9.22846, 2.01724e+06], - ["hermite", 1, 4.51682, 9.03364], - ["hermite", 2, -0.0417216, -1.99304], - ["hermite", 5, 5.07386, 87316.4], - ["hermite", 2, 4.00203, 62.065], - ["hermite", 5, -3.11819, -4956.48], - ["hermite", 1, 8.56112, 17.1222], - ["hermite", 6, -7.46692, 9.64041e+06], - ["hermite", 2, 3.2907, 41.3147], - ["hermite", 1, -4.3501, -8.7002], - ["hermite", 5, -1.24329, 63.2362], - ["hermite", 4, -8.6733, 86944.5], - ["hermite", 8, 5.82639, 2.14794e+08], - ["hermite", 6, 5.65209, 1.61959e+06], - ["hermite", 1, 0.945586, 1.89117], - ["hermite", 10, 8.14402, 9.13729e+11], - ["hermite", 2, 3.67905, 52.1416], - ["hermite", 10, 0.872528, 29975.5], - ["hermite", 10, 7.18639, 2.3345e+11], - ["hermite", 4, 1.90856, 49.4522], - ["hermite", 2, 0.0426016, -1.99274], - ["hermite", 5, -9.32589, -2.1287e+06], - ["hermite", 3, -8.01612, -4024.61], - ["hermite", 8, -7.24918, 1.46862e+09], - ["hermite", 5, 0.641412, 38.2222], - ["hermite", 0, 1.20807, 1], - ["hermite", 9, -0.799029, 3064.82], - ["hermite", 5, 6.92362, 456844], - ["hermite", 3, 2.80701, 143.254], - ["hermite", 0, -8.31758, 1], - ["hermite", 2, 0.178113, -1.8731], - ["hermite", 6, -7.16708, 7.44463e+06], - ["hermite", 4, 8.47694, 79181.3], - ["hermite", 4, 4.82454, 7563.21], - ["hermite", 3, 2.22771, 61.711], - ["hermite", 2, -2.62859, 25.6379], - ["hermite", 6, -4.40261, 299560], - ["hermite", 9, 5.38028, 9.37244e+08], - ["hermite", 9, -2.61379, 224091], - ["hermite", 9, -3.36389, -1.19209e+06], - ["hermite", 10, -8.87142, 2.28415e+12], - ["hermite", 4, 7.97235, 61596], - ["hermite", 9, 2.67941, -281217], - ["hermite", 9, 1.38544, -6245.48], - ["hermite", 0, 2.43679, 1], - ["hermite", 6, -2.25748, -446.214], - ["hermite", 0, 5.6625, 1], - ["hermite", 8, -0.514168, -998.753], - ["hermite", 2, 8.95195, 318.55], - ["hermite", 3, 5.49834, 1263.81], - ["hermite", 6, -9.35968, 3.94069e+07], - ["hermite", 8, 8.37351, 5.01699e+09], - ["hermite", 4, -1.58803, -7.29376], - ["hermite", 0, 8.33832, 1], - ["hermite", 9, 3.75904, 1.11329e+07], - ["hermite", 9, -6.92943, -1.25365e+10], - ["hermite", 4, 8.17652, 68317.5], - ["hermite", 8, -5.12804, 6.61876e+07], - ["hermite", 0, -0.319694, 1], - ["hermite", 5, -3.19578, -5828.19], - ["hermite", 1, 1.20878, 2.41755], - ["hermite", 0, 2.9429, 1], - ["hermite", 4, 4.48321, 5510.87], - ["hermite", 5, -6.61207, -358965], - ["hermite", 0, -2.52742, 1], - ["hermite", 6, -9.95631, 5.7695e+07], - ["assoc_laguerre", 8, 1, -5.56011, 15647.9], - ["assoc_laguerre", 10, 0, 4.42559, 2.02905], - ["assoc_laguerre", 6, 10, 3.41191, 609.264], - ["assoc_laguerre", 6, 9, -0.290177, 5935.75], - ["assoc_laguerre", 3, 8, 9.51122, -3.97165], - ["assoc_laguerre", 1, 5, -8.45613, 14.4561], - ["assoc_laguerre", 5, 0, -5.35991, 636.889], - ["assoc_laguerre", 8, 0, -0.547931, 11.409], - ["assoc_laguerre", 9, 0, -4.8598, 9919.3], - ["assoc_laguerre", 5, 6, -9.85883, 25624.1], - ["assoc_laguerre", 0, 0, 1.87133, 1], - ["assoc_laguerre", 6, 1, -6.85041, 5797.91], - ["assoc_laguerre", 9, 7, 0.379682, 7308.69], - ["assoc_laguerre", 8, 0, -0.881694, 27.3643], - ["assoc_laguerre", 3, 1, 1.77336, -1.28003], - ["assoc_laguerre", 8, 10, -7.53623, 2.04266e+06], - ["assoc_laguerre", 3, 8, -6.98545, 874.391], - ["assoc_laguerre", 5, 8, -9.53106, 37472.9], - ["assoc_laguerre", 2, 1, -9.79528, 80.3596], - ["assoc_laguerre", 1, 1, -3.20664, 5.20664], - ["assoc_laguerre", 2, 5, -2.26807, 39.4486], - ["assoc_laguerre", 5, 8, -9.23033, 34783.8], - ["assoc_laguerre", 5, 4, 5.0366, 4.53018], - ["assoc_laguerre", 3, 0, -4.84053, 69.5705], - ["assoc_laguerre", 0, 9, -9.21993, 1], - ["assoc_laguerre", 9, 2, 3.11624, 1.23465], - ["assoc_laguerre", 5, 7, 1.1019, 366.128], - ["assoc_laguerre", 0, 3, -1.01414, 1], - ["assoc_laguerre", 3, 7, -8.58788, 980.776], - ["assoc_laguerre", 3, 3, -0.172142, 22.6719], - ["assoc_laguerre", 2, 6, -0.349016, 30.853], - ["assoc_laguerre", 4, 4, 1.58575, 11.3493], - ["assoc_laguerre", 0, 2, -8.61307, 1], - ["assoc_laguerre", 10, 10, -5.32705, 6.85926e+06], - ["assoc_laguerre", 1, 2, 0.848012, 2.15199], - ["assoc_laguerre", 1, 8, 9.99805, -0.998052], - ["assoc_laguerre", 9, 8, -9.42609, 7.22511e+06], - ["assoc_laguerre", 4, 1, -2.00423, 52.5084], - ["assoc_laguerre", 4, 3, 7.17027, 3.927], - ["assoc_laguerre", 0, 1, -2.52939, 1], - ["assoc_laguerre", 9, 4, 4.41667, 4.89364], - ["assoc_laguerre", 7, 5, -8.34293, 156792], - ["assoc_laguerre", 9, 4, -0.631878, 1952.13], - ["assoc_laguerre", 4, 0, -8.0054, 738.433], - ["assoc_laguerre", 8, 3, -4.21376, 18061.3], - ["assoc_laguerre", 10, 8, -3.46197, 849363], - ["assoc_laguerre", 9, 5, -4.20581, 122553], - ["assoc_laguerre", 9, 5, 3.06763, -11.4039], - ["assoc_laguerre", 4, 3, -3.55097, 350.546], - ["assoc_laguerre", 9, 1, 6.55966, 4.51354], - ["assoc_laguerre", 9, 3, -9.1953, 939101], - ["assoc_laguerre", 6, 10, 4.7066, 37.6665], - ["assoc_laguerre", 8, 1, -5.28604, 12774.5], - ["assoc_laguerre", 5, 3, 5.29, 4.93518], - ["assoc_laguerre", 7, 2, -8.42112, 53112.1], - ["assoc_laguerre", 10, 2, 6.87318, 6.10542], - ["assoc_laguerre", 10, 5, 5.23115, -11.5389], - ["assoc_laguerre", 7, 4, -9.44052, 172672], - ["assoc_laguerre", 2, 10, 4.3484, 23.2735], - ["assoc_laguerre", 3, 1, -3.55595, 58.1192], - ["assoc_laguerre", 8, 6, 4.83083, 25.0254], - ["assoc_laguerre", 9, 2, -4.19255, 20351.7], - ["assoc_laguerre", 5, 2, 3.25888, 1.49267], - ["assoc_laguerre", 4, 0, -1.15903, 10.7793], - ["assoc_laguerre", 1, 4, -4.94758, 9.94758], - ["assoc_laguerre", 8, 4, -5.98204, 95371.4], - ["assoc_laguerre", 5, 3, 7.39895, -5.12281], - ["assoc_laguerre", 4, 1, -5.30576, 356.302], - ["assoc_laguerre", 4, 0, -1.94497, 25.6299], - ["assoc_laguerre", 5, 1, 6.39062, -5.78954], - ["assoc_laguerre", 1, 9, -2.63015, 12.6302], - ["assoc_laguerre", 6, 8, -9.2628, 149449], - ["assoc_laguerre", 9, 3, -4.48693, 48225.9], - ["assoc_laguerre", 1, 10, -9.96379, 20.9638], - ["assoc_laguerre", 8, 5, -6.32624, 180710], - ["assoc_laguerre", 3, 10, -5.88608, 1004.3], - ["assoc_laguerre", 6, 0, -4.96478, 1174.94], - ["assoc_laguerre", 9, 4, -8.63735, 1.0762e+06], - ["assoc_laguerre", 4, 9, 2.21793, 249.89], - ["assoc_laguerre", 9, 7, -7.85381, 2.49005e+06], - ["assoc_laguerre", 7, 4, 9.05923, 2.0395], - ["assoc_laguerre", 10, 10, -0.462794, 277334], - ["assoc_laguerre", 5, 10, -5.34582, 20021.8], - ["assoc_laguerre", 9, 3, -7.44761, 357329], - ["assoc_laguerre", 0, 0, -3.63047, 1], - ["assoc_laguerre", 9, 5, -3.45376, 70401.9], - ["assoc_laguerre", 0, 4, 0.845471, 1], - ["assoc_laguerre", 4, 4, -8.29724, 2457.57], - ["assoc_laguerre", 9, 4, -6.23466, 278328], - ["assoc_laguerre", 0, 3, -1.97705, 1], - ["assoc_laguerre", 0, 1, 1.11498, 1], - ["assoc_laguerre", 1, 6, 1.24306, 5.75694], - ["assoc_laguerre", 8, 0, 4.62047, 1.03848], - ["assoc_laguerre", 3, 4, 5.58716, -2.14157], - ["assoc_laguerre", 7, 6, 1.26093, 364.593], - ["assoc_laguerre", 8, 10, -3.99046, 449423], - ["assoc_laguerre", 3, 3, 0.343607, 15.1933], - ["assoc_laguerre", 3, 6, 9.11024, 3.49586], - ["assoc_laguerre", 7, 7, 5.25613, -1.90456], - ["assoc_laguerre", 3, 3, -4.33736, 155.098], - ["assoc_legendre", 5, 6, 0.246109, 0], - ["assoc_legendre", 7, 9, 0.0959347, 0], - ["assoc_legendre", 9, 10, 0.799802, 0], - ["assoc_legendre", 9, 2, -0.364322, -7.6804], - ["assoc_legendre", 3, 6, -0.954549, 0], - ["assoc_legendre", 7, 1, 0.78675, 2.52538], - ["assoc_legendre", 5, 7, -0.455507, 0], - ["assoc_legendre", 9, 10, -0.618458, 0], - ["assoc_legendre", 0, 2, -0.249328, 0], - ["assoc_legendre", 9, 10, 0.414676, 0], - ["assoc_legendre", 2, 7, 0.0744382, 0], - ["assoc_legendre", 6, 9, 0.603221, 0], - ["assoc_legendre", 9, 10, -0.469774, 0], - ["assoc_legendre", 9, 8, -0.69662, -1.68497e+06], - ["assoc_legendre", 5, 5, 0.453746, -531.055], - ["assoc_legendre", 5, 6, 0.610315, 0], - ["assoc_legendre", 2, 2, -0.685753, 1.58923], - ["assoc_legendre", 0, 4, 0.704456, 0], - ["assoc_legendre", 6, 5, -0.981828, 2.51222], - ["assoc_legendre", 2, 6, -0.545978, 0], - ["assoc_legendre", 2, 1, -0.118695, 0.353568], - ["assoc_legendre", 6, 0, 0.89993, -0.241552], - ["assoc_legendre", 7, 3, -0.82078, -172.023], - ["assoc_legendre", 2, 0, 0.18563, -0.448312], - ["assoc_legendre", 10, 4, 0.356737, 2707.55], - ["assoc_legendre", 7, 8, -0.971158, 0], - ["assoc_legendre", 5, 5, -0.656202, -231.193], - ["assoc_legendre", 5, 5, 0.0633444, -935.549], - ["assoc_legendre", 9, 2, -0.979377, -29.8628], - ["assoc_legendre", 2, 7, -0.605857, 0], - ["assoc_legendre", 2, 10, 0.328756, 0], - ["assoc_legendre", 7, 4, 0.230915, -827.072], - ["assoc_legendre", 2, 1, -0.305359, 0.872322], - ["assoc_legendre", 1, 3, -0.452583, 0], - ["assoc_legendre", 8, 9, -0.764506, 0], - ["assoc_legendre", 6, 3, -0.190821, -73.8969], - ["assoc_legendre", 4, 8, 0.885521, 0], - ["assoc_legendre", 0, 4, 0.933209, 0], - ["assoc_legendre", 0, 10, -0.415395, 0], - ["assoc_legendre", 2, 2, -0.656632, 1.7065], - ["assoc_legendre", 4, 5, 0.692216, 0], - ["assoc_legendre", 1, 2, -0.223691, 0], - ["assoc_legendre", 9, 8, 0.475711, 5.87408e+06], - ["assoc_legendre", 4, 3, -0.868657, 11.0902], - ["assoc_legendre", 6, 0, -0.574362, 0.228182], - ["assoc_legendre", 6, 7, 0.372751, 0], - ["assoc_legendre", 6, 9, 0.919761, 0], - ["assoc_legendre", 6, 8, -0.275332, 0], - ["assoc_legendre", 2, 0, 0.75034, 0.344515], - ["assoc_legendre", 3, 6, -0.312883, 0], - ["assoc_legendre", 5, 1, 0.632117, 1.80332], - ["assoc_legendre", 3, 5, 0.00540365, 0], - ["assoc_legendre", 4, 3, 0.798751, -18.2666], - ["assoc_legendre", 0, 7, 0.100493, 0], - ["assoc_legendre", 10, 2, 0.513729, 21.9344], - ["assoc_legendre", 7, 3, -0.149192, -60.977], - ["assoc_legendre", 10, 3, 0.757559, 277.028], - ["assoc_legendre", 4, 0, 0.937364, 0.457677], - ["assoc_legendre", 3, 4, 0.639471, 0], - ["assoc_legendre", 7, 8, 0.397962, 0], - ["assoc_legendre", 9, 8, -0.970039, -405.702], - ["assoc_legendre", 8, 7, 0.181088, -326639], - ["assoc_legendre", 2, 10, 0.674011, 0], - ["assoc_legendre", 0, 4, -0.100379, 0], - ["assoc_legendre", 6, 10, 0.993968, 0], - ["assoc_legendre", 7, 10, -0.305816, 0], - ["assoc_legendre", 4, 8, -0.20189, 0], - ["assoc_legendre", 2, 8, -0.830613, 0], - ["assoc_legendre", 9, 0, -0.0967429, -0.206575], - ["assoc_legendre", 6, 0, 0.731047, -0.224596], - ["assoc_legendre", 0, 2, -0.3419, 0], - ["assoc_legendre", 8, 6, -0.0492673, -64634.5], - ["assoc_legendre", 7, 9, -0.0206372, 0], - ["assoc_legendre", 4, 4, -0.717119, 24.7741], - ["assoc_legendre", 3, 7, -0.355589, 0], - ["assoc_legendre", 0, 8, -0.89528, 0], - ["assoc_legendre", 9, 8, 0.277641, 6.94127e+06], - ["assoc_legendre", 9, 1, -0.776337, 1.60341], - ["assoc_legendre", 2, 2, 0.0240907, 2.99826], - ["assoc_legendre", 2, 5, -0.474824, 0], - ["assoc_legendre", 0, 9, -0.039836, 0], - ["assoc_legendre", 0, 0, 0.784754, 1], - ["assoc_legendre", 6, 1, 0.614487, 2.06507], - ["assoc_legendre", 5, 4, 0.666625, 194.471], - ["assoc_legendre", 0, 4, -0.395557, 0], - ["assoc_legendre", 8, 10, 0.290334, 0], - ["assoc_legendre", 6, 8, 0.171052, 0], - ["assoc_legendre", 10, 10, 0.0301052, 6.51767e+08], - ["assoc_legendre", 5, 9, 0.932685, 0], - ["assoc_legendre", 2, 0, 0.649127, 0.132049], - ["assoc_legendre", 10, 8, -0.458004, 2.00598e+07], - ["assoc_legendre", 4, 3, -0.751059, 22.6965], - ["assoc_legendre", 4, 4, 0.216443, 95.3924], - ["assoc_legendre", 6, 2, -0.62567, -7.90168], - ["assoc_legendre", 0, 4, 0.299177, 0], - ["assoc_legendre", 8, 0, 0.165673, 0.0421266], - ["assoc_legendre", 1, 3, 0.749081, 0], - ["assoc_legendre", 10, 7, -0.438055, 770953], - ["assoc_legendre", 10, 10, 0.503198, 1.52076e+08], - ["assoc_legendre", 6, 8, -0.400661, 0], - ["riemann_zeta", 1.18576, 5.97385], - ["riemann_zeta", 9.1875, 1.00176], - ["riemann_zeta", 5.58812, 1.02359], - ["riemann_zeta", 7.35446, 1.00647], - ["riemann_zeta", 1.25539, 4.51107], - ["riemann_zeta", 7.61548, 1.00536], - ["riemann_zeta", -2.78231, 0.00911049], - ["riemann_zeta", 2.97002, 1.20811], - ["riemann_zeta", 8.2331, 1.00345], - ["riemann_zeta", 5.58753, 1.0236], - ["riemann_zeta", -9.26353, -0.00776192], - ["riemann_zeta", -3.34015, 0.00586759], - ["riemann_zeta", 9.29878, 1.00163], - ["riemann_zeta", -2.78366, 0.00910845], - ["riemann_zeta", 4.27491, 1.06561], - ["riemann_zeta", -6.48105, 0.00265857], - ["riemann_zeta", 6.88098, 1.0091], - ["riemann_zeta", 2.56604, 1.31712], - ["riemann_zeta", -1.03913, -0.0770475], - ["riemann_zeta", -5.05815, -0.00391993], - ["riemann_zeta", -9.50369, -0.00664474], - ["riemann_zeta", 3.61958, 1.11401], - ["riemann_zeta", -8.6527, -0.00564677], - ["riemann_zeta", -6.41665, 0.00234529], - ["riemann_zeta", 5.28373, 1.0297], - ["riemann_zeta", 7.94791, 1.00423], - ["riemann_zeta", 8.44276, 1.00298], - ["riemann_zeta", 9.59082, 1.00133], - ["riemann_zeta", 6.85688, 1.00926], - ["riemann_zeta", 7.78719, 1.00475], - ["riemann_zeta", 0.840867, -5.71853], - ["riemann_zeta", -4.76773, -0.00385361], - ["riemann_zeta", -4.5256, -0.00319357], - ["riemann_zeta", 8.95004, 1.00208], - ["riemann_zeta", -2.59764, 0.008975], - ["riemann_zeta", -2.46923, 0.00830787], - ["riemann_zeta", 6.585, 1.01128], - ["riemann_zeta", 0.299112, -0.902819], - ["riemann_zeta", -5.67982, -0.0018085], - ["riemann_zeta", 5.39082, 1.02738], - ["riemann_zeta", -4.68787, -0.00369718], - ["riemann_zeta", -5.01897, -0.00395578], - ["riemann_zeta", -2.86789, 0.00890723], - ["riemann_zeta", 6.62512, 1.01096], - ["riemann_zeta", 0.563095, -1.74432], - ["riemann_zeta", -0.318079, -0.284759], - ["riemann_zeta", 2.49736, 1.34251], - ["riemann_zeta", -8.12124, -0.00104034], - ["riemann_zeta", -6.90041, 0.00404745], - ["riemann_zeta", -7.78105, 0.00167594], - ["riemann_zeta", -0.555241, -0.18883], - ["riemann_zeta", -9.52722, -0.0064623], - ["riemann_zeta", -1.50551, -0.0250665], - ["riemann_zeta", 3.83129, 1.09494], - ["riemann_zeta", -9.41783, -0.00719791], - ["riemann_zeta", 0.989137, -91.4817], - ["riemann_zeta", -0.414784, -0.240932], - ["riemann_zeta", 6.17256, 1.01527], - ["riemann_zeta", 2.0869, 1.57037], - ["riemann_zeta", 6.41624, 1.01276], - ["riemann_zeta", -5.5688, -0.00235996], - ["riemann_zeta", -1.13806, -0.0627227], - ["riemann_zeta", -2.42862, 0.00798053], - ["riemann_zeta", 6.07372, 1.01642], - ["riemann_zeta", -9.85926, -0.0024607], - ["riemann_zeta", 1.43837, 2.88937], - ["riemann_zeta", 8.71608, 1.00245], - ["riemann_zeta", -3.24376, 0.00666953], - ["riemann_zeta", -6.30527, 0.00176085], - ["riemann_zeta", -2.06886, 0.00194524], - ["riemann_zeta", 7.49139, 1.00586], - ["riemann_zeta", -2.12126, 0.00323249], - ["riemann_zeta", 1.07419, 14.0622], - ["riemann_zeta", -6.45054, 0.00251268], - ["riemann_zeta", -7.47991, 0.00335443], - ["riemann_zeta", 2.7766, 1.25308], - ["riemann_zeta", 7.83887, 1.00457], - ["riemann_zeta", 5.1833, 1.03207], - ["riemann_zeta", 3.04372, 1.19362], - ["riemann_zeta", -4.2629, -0.00187126], - ["riemann_zeta", -6.41217, 0.00232279], - ["riemann_zeta", -2.34414, 0.00709775], - ["riemann_zeta", -9.24886, -0.00778802], - ["riemann_zeta", 2.04437, 1.60521], - ["riemann_zeta", 8.45229, 1.00296], - ["riemann_zeta", -3.23682, 0.00672484], - ["riemann_zeta", 3.79976, 1.09753], - ["riemann_zeta", 5.6916, 1.02182], - ["riemann_zeta", -8.94566, -0.00738175], - ["riemann_zeta", -7.46082, 0.00343178], - ["riemann_zeta", 0.853436, -6.2565], - ["riemann_zeta", -1.48197, -0.0268811], - ["riemann_zeta", 3.91482, 1.08844], - ["riemann_zeta", -4.4857, -0.00303214], - ["riemann_zeta", 5.53541, 1.02454], - ["riemann_zeta", 4.83155, 1.0421], - ["riemann_zeta", -1.46733, -0.0280456], - ["riemann_zeta", 6.36686, 1.01323], - ["riemann_zeta", 7.68771, 1.00509], - ["riemann_zeta", -0.724008, -0.140067], - ["clamp", 1, 6, 5, 5] -] \ No newline at end of file + ["cyl_bessel_i", -8.22945, 2.22939, 582.734], + ["cyl_bessel_j", -8.22945, 2.22939, 821.955], + ["cyl_bessel_k", -8.22945, 2.22939, 1386.88], + ["cyl_neumann", -8.22945, 2.22939, -935.585], + ["sph_bessel", 1, 2.22939, 0.433637], + ["sph_neumann", 1, 2.22939, -0.231604], + ["cyl_bessel_i", -2, -8.60511, 589.337], + ["cyl_bessel_j", -2, -8.60511, 0.0501442], + ["cyl_bessel_k", -1.95539, 8.60511, 9.52189e-5], + ["cyl_neumann", -1.95539, 8.60511, -0.273857], + ["sph_bessel", 0, 8.60511, 0.0849398], + ["sph_neumann", 0, 8.60511, 0.0793094], + ["cyl_bessel_i", -6.70685, 5.95949, 1.61543], + ["cyl_bessel_j", -6.70685, 5.95949, 0.376504], + ["cyl_bessel_k", -6.70685, 5.95949, 0.0348366], + ["cyl_neumann", -6.70685, 5.95949, 0.481466], + ["sph_bessel", 2, 5.95949, -0.0312186], + ["sph_neumann", 2, 5.95949, 0.172515], + ["cyl_bessel_i", -9.7301, 7.68293, 0.908489], + ["cyl_bessel_j", -9.7301, 7.68293, -0.678491], + ["cyl_bessel_k", -9.7301, 7.68293, 0.0433752], + ["cyl_neumann", -9.7301, 7.68293, -0.675836], + ["sph_bessel", 0, 7.68293, 0.128259], + ["sph_neumann", 0, 7.68293, -0.0221551], + ["cyl_bessel_i", -2.06486, 0.603805, 0.767621], + ["cyl_bessel_j", -2.06486, 0.603805, 0.899114], + ["cyl_bessel_k", -2.06486, 0.603805, 5.64132], + ["cyl_neumann", -2.06486, 0.603805, -4.16093], + ["sph_bessel", 7, 0.603805, 1.42809e-8], + ["sph_neumann", 7, 0.603805, -7.75701e6], + ["cyl_bessel_i", 8.62319, 9.15733, 23.4759], + ["cyl_bessel_j", 8.62319, 9.15733, 0.264633], + ["cyl_bessel_k", 8.62319, 9.15733, 0.0016923], + ["cyl_neumann", 8.62319, 9.15733, -0.283982], + ["sph_bessel", 7, 9.15733, 0.136994], + ["sph_neumann", 7, 9.15733, -0.0261161], + ["cyl_bessel_i", 9, -0.328577, -2.40921e-13], + ["cyl_bessel_j", 9, -0.328577, -2.39624e-13], + ["cyl_bessel_k", 9.32857, 0.328577, 8.48266e11], + ["cyl_neumann", 9.32857, 0.328577, -5.43535e11], + ["sph_bessel", 6, 0.328577, 9.27881e-9], + ["sph_neumann", 6, 0.328577, -2.52637e7], + ["cyl_bessel_i", 4, -6.30895, 23.6382], + ["cyl_bessel_j", 4, -6.30895, 0.3112], + ["cyl_bessel_k", 4.76613, 6.30895, 0.00452921], + ["cyl_neumann", 4.76613, 6.30895, -0.0486063], + ["sph_bessel", 6, 6.30895, 0.108794], + ["sph_neumann", 6, 6.30895, -0.228437], + ["cyl_bessel_i", -8, -3.30098, 0.00184039], + ["cyl_bessel_j", -8, -3.30098, 0.00100429], + ["cyl_bessel_k", -7.88289, 3.30098, 26.1357], + ["cyl_neumann", -7.88289, 3.30098, -34.3665], + ["sph_bessel", 1, 3.30098, 0.284536], + ["sph_neumann", 1, 3.30098, 0.138689], + ["cyl_bessel_i", -10, -0.507934, 3.09428e-13], + ["cyl_bessel_j", -10, -0.507934, 3.05821e-13], + ["cyl_bessel_k", -9.47574, 0.507934, 2.45082e10], + ["cyl_neumann", -9.47574, 0.507934, 1.20617e9], + ["sph_bessel", 9, 0.507934, 3.41617e-12], + ["sph_neumann", 9, 0.507934, -3.03758e10], + ["cyl_bessel_i", 8.95185, 9.40842, 24.7422], + ["cyl_bessel_j", 8.95185, 9.40842, 0.254767], + ["cyl_bessel_k", 8.95185, 9.40842, 0.00155526], + ["cyl_neumann", 8.95185, 9.40842, -0.295027], + ["sph_bessel", 5, 9.40842, -0.0050529], + ["sph_neumann", 5, 9.40842, 0.117315], + ["cyl_bessel_i", -6.2007, 6.22679, 3.81316], + ["cyl_bessel_j", -6.2007, 6.22679, 0.444251], + ["cyl_bessel_k", -6.2007, 6.22679, 0.0149256], + ["cyl_neumann", -6.2007, 6.22679, -0.191143], + ["sph_bessel", 0, 6.22679, -0.00905235], + ["sph_neumann", 0, 6.22679, -0.160341], + ["cyl_bessel_i", 8.96131, 7.97894, 3.2635], + ["cyl_bessel_j", 8.96131, 7.97894, 0.127826], + ["cyl_bessel_k", 8.96131, 7.97894, 0.0127601], + ["cyl_neumann", 8.96131, 7.97894, -0.571977], + ["sph_bessel", 1, 7.97894, 0.0312054], + ["sph_neumann", 1, 7.97894, -0.122395], + ["cyl_bessel_i", -9, -9.30887, -20.7158], + ["cyl_bessel_j", -9, -9.30887, 0.242028], + ["cyl_bessel_k", -8.27207, 9.30887, 0.00103801], + ["cyl_neumann", -8.27207, 9.30887, 0.102256], + ["sph_bessel", 7, 9.30887, 0.135061], + ["sph_neumann", 7, 9.30887, -0.0127884], + ["cyl_bessel_i", 2.67713, 1.64132, 0.173622], + ["cyl_bessel_j", 2.67713, 1.64132, 0.120333], + ["cyl_bessel_k", 2.67713, 1.64132, 0.909297], + ["cyl_neumann", 2.67713, 1.64132, -1.28718], + ["sph_bessel", 0, 1.64132, 0.60775], + ["sph_neumann", 0, 1.64132, 0.0429334], + ["cyl_bessel_i", -4, -3.04496, 0.350084], + ["cyl_bessel_j", -4, -3.04496, 0.138073], + ["cyl_bessel_k", -3.37257, 3.04496, 0.156158], + ["cyl_neumann", -3.37257, 3.04496, 0.0268717], + ["sph_bessel", 7, 3.04496, 0.000907869], + ["sph_neumann", 7, 3.04496, -26.4652], + ["cyl_bessel_i", -5, -7.73585, -63.2894], + ["cyl_bessel_j", -5, -7.73585, 0.240928], + ["cyl_bessel_k", -4.42534, 7.73585, 0.000624919], + ["cyl_neumann", -4.42534, 7.73585, 0.160469], + ["sph_bessel", 10, 7.73585, 0.0140547], + ["sph_neumann", 10, 7.73585, -0.667576], + ["cyl_bessel_i", 9.79562, 0.663139, 9.04206e-12], + ["cyl_bessel_j", 9.79562, 0.663139, 8.85976e-12], + ["cyl_bessel_k", 9.79562, 0.663139, 5.63206e9], + ["cyl_neumann", 9.79562, 0.663139, -3.67624e9], + ["sph_bessel", 3, 0.663139, 0.00271014], + ["sph_neumann", 3, 0.663139, -81.1107], + ["cyl_bessel_i", -0.658851, 8.69203, 796.805], + ["cyl_bessel_j", -0.658851, 8.69203, -0.2411], + ["cyl_bessel_k", -0.658851, 8.69203, 7.21036e-5], + ["cyl_neumann", -0.658851, 8.69203, 0.12329], + ["sph_bessel", 6, 8.69203, 0.135549], + ["sph_neumann", 6, 8.69203, 0.0290624], + ["cyl_bessel_i", -3, -7.05845, -90.444], + ["cyl_bessel_j", -3, -7.05845, -0.180681], + ["cyl_bessel_k", -2.46092, 7.05845, 0.000595037], + ["cyl_neumann", -2.46092, 7.05845, -0.27916], + ["sph_bessel", 6, 7.05845, 0.139847], + ["sph_neumann", 6, 7.05845, -0.139775], + ["cyl_bessel_i", -9, -1.6091, -4.15188e-7], + ["cyl_bessel_j", -9, -1.6091, 3.64771e-7], + ["cyl_bessel_k", -8.38449, 1.6091, 31351.1], + ["cyl_neumann", -8.38449, 1.6091, -8442.74], + ["sph_bessel", 10, 1.6091, 7.99927e-9], + ["sph_neumann", 10, 1.6091, -3.74419e6], + ["cyl_bessel_i", -8, -9.78718, 88.8396], + ["cyl_bessel_j", -8, -9.78718, 0.323376], + ["cyl_bessel_k", -7.57722, 9.78718, 0.000330236], + ["cyl_neumann", -7.57722, 9.78718, -0.28924], + ["sph_bessel", 6, 9.78718, 0.0626841], + ["sph_neumann", 6, 9.78718, 0.0990758], + ["cyl_bessel_i", 6.37191, 3.68549, 0.0527286], + ["cyl_bessel_j", 6.37191, 3.68549, 0.0209519], + ["cyl_bessel_k", 6.37191, 3.68549, 1.2862], + ["cyl_neumann", 6.37191, 3.68549, -2.9783], + ["sph_bessel", 1, 3.68549, 0.194084], + ["sph_neumann", 1, 3.68549, 0.203407], + ["cyl_bessel_i", 5.44232, 8.02878, 66.5237], + ["cyl_bessel_j", 5.44232, 8.02878, 0.271855], + ["cyl_bessel_k", 5.44232, 8.02878, 0.000774483], + ["cyl_neumann", 5.44232, 8.02878, 0.177208], + ["sph_bessel", 9, 8.02878, 0.0403048], + ["sph_neumann", 9, 8.02878, -0.309241], + ["cyl_bessel_i", -3, -9.10705, -720.003], + ["cyl_bessel_j", -3, -9.10705, -0.158221], + ["cyl_bessel_k", -2.86788, 9.10705, 6.96325e-5], + ["cyl_neumann", -2.86788, 9.10705, 0.17432], + ["sph_bessel", 10, 9.10705, 0.0400525], + ["sph_neumann", 10, 9.10705, -0.262887], + ["cyl_bessel_i", 5.32167, 1.76282, 0.00275211], + ["cyl_bessel_j", 5.32167, 1.76282, 0.00215231], + ["cyl_bessel_k", 5.32167, 1.76282, 32.3629], + ["cyl_neumann", 5.32167, 1.76282, -29.5485], + ["sph_bessel", 6, 1.76282, 0.000200087], + ["sph_neumann", 6, 1.76282, -226.846], + ["cyl_bessel_i", 7.98608, 4.80589, 0.0523349], + ["cyl_bessel_j", 7.98608, 4.80589, 0.0144294], + ["cyl_bessel_k", 7.98608, 4.80589, 1.02399], + ["cyl_neumann", 7.98608, 4.80589, -3.51129], + ["sph_bessel", 0, 4.80589, -0.207169], + ["sph_neumann", 0, 4.80589, -0.0194281], + ["cyl_bessel_i", 4.72929, 7.10757, 36.6466], + ["cyl_bessel_j", 4.72929, 7.10757, 0.302032], + ["cyl_bessel_k", 4.72929, 7.10757, 0.00159711], + ["cyl_neumann", 4.72929, 7.10757, 0.160144], + ["sph_bessel", 5, 7.10757, 0.1702], + ["sph_neumann", 5, 7.10757, -0.0216967], + ["cyl_bessel_i", 0, -7.84614, 370.3], + ["cyl_bessel_j", 0, -7.84614, 0.205918], + ["cyl_bessel_k", 0.378608, 7.84614, 0.000173945], + ["cyl_neumann", 0.378608, 7.84614, 0.0498821], + ["sph_bessel", 3, 7.84614, -0.0927464], + ["sph_neumann", 3, 7.84614, 0.0971267], + ["cyl_bessel_i", -5, -9.62295, -516.817], + ["cyl_bessel_j", -5, -9.62295, -0.182905], + ["cyl_bessel_k", -4.84577, 9.62295, 8.29446e-5], + ["cyl_neumann", -4.84577, 9.62295, -0.254573], + ["sph_bessel", 10, 9.62295, 0.0537971], + ["sph_neumann", 10, 9.62295, -0.204458], + ["cyl_bessel_i", 3, -1.63886, -0.10817], + ["cyl_bessel_j", 3, -1.63886, -0.0773049], + ["cyl_bessel_k", 3.81265, 1.63886, 4.06086], + ["cyl_neumann", 3.81265, 1.63886, -4.20015], + ["sph_bessel", 4, 1.63886, 0.00674844], + ["sph_neumann", 4, 1.63886, -10.8569], + ["cyl_bessel_i", -4.59451, 9.43359, 517.613], + ["cyl_bessel_j", -4.59451, 9.43359, -0.0800797], + ["cyl_bessel_k", -4.59451, 9.43359, 9.20612e-5], + ["cyl_neumann", -4.59451, 9.43359, -0.265383], + ["sph_bessel", 0, 9.43359, -0.000934566], + ["sph_neumann", 0, 9.43359, 0.106], + ["cyl_bessel_i", -5, -2.21913, -0.0171567], + ["cyl_bessel_j", -5, -2.21913, 0.0113794], + ["cyl_bessel_k", -4.11935, 2.21913, 1.57664], + ["cyl_neumann", -4.11935, 2.21913, -2.08678], + ["sph_bessel", 10, 2.21913, 1.89171e-7], + ["sph_neumann", 10, 2.21913, -116083], + ["cyl_bessel_i", -1, -2.46505, -2.43812], + ["cyl_bessel_j", -1, -2.46505, 0.505539], + ["cyl_bessel_k", -0.947493, 2.46505, 0.0758422], + ["cyl_neumann", -0.947493, 2.46505, -0.0778582], + ["sph_bessel", 3, 2.46505, 0.100655], + ["sph_neumann", 3, 2.46505, -0.826162], + ["cyl_bessel_i", -9, -5.87524, -0.103164], + ["cyl_bessel_j", -9, -5.87524, 0.0182431], + ["cyl_bessel_k", -8.79749, 5.87524, 0.355913], + ["cyl_neumann", -8.79749, 5.87524, 1.78094], + ["sph_bessel", 8, 5.87524, 0.015894], + ["sph_neumann", 8, 5.87524, -0.896546], + ["cyl_bessel_i", -9, -8.25974, -4.73931], + ["cyl_bessel_j", -9, -8.25974, 0.148174], + ["cyl_bessel_k", -8.91871, 8.25974, 0.00801487], + ["cyl_neumann", -8.91871, 8.25974, 0.52102], + ["sph_bessel", 6, 8.25974, 0.149451], + ["sph_neumann", 6, 8.25974, -0.0118069], + ["cyl_bessel_i", -9.52125, 5.81788, -0.549704], + ["cyl_bessel_j", -9.52125, 5.81788, -4.49319], + ["cyl_bessel_k", -9.52125, 5.81788, 0.940366], + ["cyl_neumann", -9.52125, 5.81788, -0.309867], + ["sph_bessel", 5, 5.81788, 0.150915], + ["sph_neumann", 5, 5.81788, -0.18871], + ["cyl_bessel_i", 6, -2.84868, 0.0154181], + ["cyl_bessel_j", 6, -2.84868, 0.00863176], + ["cyl_bessel_k", 6.49451, 2.84868, 10.0404], + ["cyl_neumann", 6.49451, 2.84868, -13.4401], + ["sph_bessel", 10, 2.84868, 2.14285e-6], + ["sph_neumann", 10, 2.84868, -8108.42], + ["cyl_bessel_i", 6, -5.24377, 1.14257], + ["cyl_bessel_j", 6, -5.24377, 0.157381], + ["cyl_bessel_k", 6.87921, 5.24377, 0.130792], + ["cyl_neumann", 6.87921, 5.24377, -0.971137], + ["sph_bessel", 2, 5.24377, 0.0911837], + ["sph_neumann", 2, 5.24377, 0.180149], + ["cyl_bessel_i", 0.362031, 1.11278, 1.12922], + ["cyl_bessel_j", 0.362031, 1.11278, 0.715306], + ["cyl_bessel_k", 0.362031, 1.11278, 0.37528], + ["cyl_neumann", 0.362031, 1.11278, -0.209679], + ["sph_bessel", 4, 1.11278, 0.00153342], + ["sph_neumann", 4, 1.11278, -67.3429], + ["cyl_bessel_i", 2, -7.22511, 154.351], + ["cyl_bessel_j", 2, -7.22511, -0.276588], + ["cyl_bessel_k", 2.2542, 7.22511, 0.000463835], + ["cyl_neumann", 2.2542, 7.22511, -0.0275572], + ["sph_bessel", 5, 7.22511, 0.167217], + ["sph_neumann", 5, 7.22511, -0.0078814], + ["cyl_bessel_i", -4.4206, 9.76369, 798.377], + ["cyl_bessel_j", -4.4206, 9.76369, -0.094454], + ["cyl_bessel_k", -4.4206, 9.76369, 5.84398e-5], + ["cyl_neumann", -4.4206, 9.76369, -0.25276], + ["sph_bessel", 3, 9.76369, -0.0610195], + ["sph_neumann", 3, 9.76369, -0.0864953], + ["cyl_bessel_i", 5, -8.51223, -152.236], + ["cyl_bessel_j", 5, -8.51223, -0.0641093], + ["cyl_bessel_k", 5.18537, 8.51223, 0.000367838], + ["cyl_neumann", 5.18537, 8.51223, 0.282322], + ["sph_bessel", 10, 8.51223, 0.0266945], + ["sph_neumann", 10, 8.51223, -0.371547], + ["cyl_bessel_i", 4.38995, 6.85753, 34.3079], + ["cyl_bessel_j", 4.38995, 6.85753, 0.28507], + ["cyl_bessel_k", 4.38995, 6.85753, 0.00178876], + ["cyl_neumann", 4.38995, 6.85753, 0.191756], + ["sph_bessel", 7, 6.85753, 0.0779504], + ["sph_neumann", 7, 6.85753, -0.255544], + ["cyl_bessel_i", 1.39952, 3.65061, 6.11313], + ["cyl_bessel_j", 1.39952, 3.65061, 0.269348], + ["cyl_bessel_k", 1.39952, 3.65061, 0.0209586], + ["cyl_neumann", 1.39952, 3.65061, 0.335957], + ["sph_bessel", 5, 3.65061, 0.0366524], + ["sph_neumann", 5, 3.65061, -0.941477], + ["cyl_bessel_i", -7.20821, 1.37525, -2849.36], + ["cyl_bessel_j", -7.20821, 1.37525, -3318.27], + ["cyl_bessel_k", -7.20821, 1.37525, 7355.99], + ["cyl_neumann", -7.20821, 1.37525, 4327.96], + ["sph_bessel", 0, 1.37525, 0.713283], + ["sph_neumann", 0, 1.37525, -0.141286], + ["cyl_bessel_i", 4.07478, 0.606964, 0.000293959], + ["cyl_bessel_j", 4.07478, 0.606964, 0.00028348], + ["cyl_bessel_k", 4.07478, 0.606964, 412.602], + ["cyl_neumann", 4.07478, 0.606964, -278.892], + ["sph_bessel", 8, 0.606964, 5.29399e-10], + ["sph_neumann", 8, 0.606964, -1.8354e8], + ["cyl_bessel_i", 0.30233, 0.922756, 1.03325], + ["cyl_bessel_j", 0.30233, 0.922756, 0.744555], + ["cyl_bessel_k", 0.30233, 0.922756, 0.487755], + ["cyl_neumann", 0.30233, 0.922756, -0.318843], + ["sph_bessel", 9, 0.922756, 7.25951e-10], + ["sph_neumann", 9, 0.922756, -7.89467e7], + ["cyl_bessel_i", -7, -2.40931, -0.000874213], + ["cyl_bessel_j", -7, -2.40931, 0.000608159], + ["cyl_bessel_k", -6.00016, 2.40931, 14.8294], + ["cyl_neumann", -6.00016, 2.40931, -16.9195], + ["sph_bessel", 6, 2.40931, 0.00119008], + ["sph_neumann", 6, 2.40931, -28.9702], + ["cyl_bessel_i", -9, -2.22862, -8.25894e-6], + ["cyl_bessel_j", -9, -2.22862, 6.44264e-6], + ["cyl_bessel_k", -8.83124, 2.22862, 4625], + ["cyl_neumann", -8.83124, 2.22862, 3488.49], + ["sph_bessel", 0, 2.22862, 0.355072], + ["sph_neumann", 0, 2.22862, 0.274339], + ["cyl_bessel_i", -5, -6.4547, -13.9761], + ["cyl_bessel_j", -5, -6.4547, 0.37398], + ["cyl_bessel_k", -4.38636, 6.4547, 0.00295444], + ["cyl_neumann", -4.38636, 6.4547, 0.359627], + ["sph_bessel", 6, 6.4547, 0.115618], + ["sph_neumann", 6, 6.4547, -0.209864], + ["cyl_bessel_i", -3, -4.18761, -4.15215], + ["cyl_bessel_j", -3, -4.18761, 0.434375], + ["cyl_bessel_k", -2.91715, 4.18761, 0.022177], + ["cyl_neumann", -2.91715, 4.18761, 0.194412], + ["sph_bessel", 5, 4.18761, 0.060996], + ["sph_neumann", 5, 4.18761, -0.563614], + ["cyl_bessel_i", -8, -9.37862, 52.8172], + ["cyl_bessel_j", -8, -9.37862, 0.320845], + ["cyl_bessel_k", -7.30167, 9.37862, 0.000464247], + ["cyl_neumann", -7.30167, 9.37862, -0.276694], + ["sph_bessel", 9, 9.37862, 0.0820221], + ["sph_neumann", 9, 9.37862, -0.158127], + ["cyl_bessel_i", -8.32791, 5.17016, 0.484525], + ["cyl_bessel_j", -8.32791, 5.17016, 2.69568], + ["cyl_bessel_k", -8.32791, 5.17016, 0.765773], + ["cyl_neumann", -8.32791, 5.17016, -1.59978], + ["sph_bessel", 7, 5.17016, 0.021403], + ["sph_neumann", 7, 5.17016, -0.858511], + ["cyl_bessel_i", -8.60378, 8.61616, 11.414], + ["cyl_bessel_j", -8.60378, 8.61616, 0.286105], + ["cyl_bessel_k", -8.60378, 8.61616, 0.00359605], + ["cyl_neumann", -8.60378, 8.61616, 0.328193], + ["sph_bessel", 4, 8.61616, -0.0451936], + ["sph_neumann", 4, 8.61616, 0.116743], + ["cyl_bessel_i", -3, -3.02862, -0.997158], + ["cyl_bessel_j", -3, -3.02862, 0.314104], + ["cyl_bessel_k", -2.22897, 3.02862, 0.0677352], + ["cyl_neumann", -2.22897, 3.02862, 0.116108], + ["sph_bessel", 0, 3.02862, 0.037223], + ["sph_neumann", 0, 3.02862, 0.328079], + ["cyl_bessel_i", 4.51373, 3.78436, 0.618056], + ["cyl_bessel_j", 4.51373, 3.78436, 0.167374], + ["cyl_bessel_k", 4.51373, 3.78436, 0.136957], + ["cyl_neumann", 4.51373, 3.78436, -0.713284], + ["sph_bessel", 8, 3.78436, 0.000831532], + ["sph_neumann", 8, 3.78436, -20.9409], + ["cyl_bessel_i", -3.60386, 2.84588, 0.243414], + ["cyl_bessel_j", -3.60386, 2.84588, -0.724026], + ["cyl_bessel_k", -3.60386, 2.84588, 0.267719], + ["cyl_neumann", -3.60386, 2.84588, -0.421797], + ["sph_bessel", 9, 2.84588, 1.53967e-5], + ["sph_neumann", 9, 2.84588, -1259.85], + ["cyl_bessel_i", -5.75359, 9.72933, 382.911], + ["cyl_bessel_j", -5.75359, 9.72933, 0.184816], + ["cyl_bessel_k", -5.75359, 9.72933, 0.000115497], + ["cyl_neumann", -5.75359, 9.72933, 0.214955], + ["sph_bessel", 4, 9.72933, -0.106131], + ["sph_neumann", 4, 9.72933, 0.0244245], + ["cyl_bessel_i", -6.38851, 1.07125, 3611.61], + ["cyl_bessel_j", -6.38851, 1.07125, 4017.46], + ["cyl_bessel_k", -6.38851, 1.07125, 6039.79], + ["cyl_neumann", -6.38851, 1.07125, -1467.61], + ["sph_bessel", 2, 1.07125, 0.0704305], + ["sph_neumann", 2, 1.07125, -3.01657], + ["cyl_bessel_i", -3, -5.17516, -12.5037], + ["cyl_bessel_j", -3, -5.17516, 0.331681], + ["cyl_bessel_k", -2.53716, 5.17516, 0.00535694], + ["cyl_neumann", -2.53716, 5.17516, 0.163107], + ["sph_bessel", 8, 5.17516, 0.00719078], + ["sph_neumann", 8, 5.17516, -2.02119], + ["cyl_bessel_i", 1.83729, 2.4805, 1.42753], + ["cyl_bessel_j", 1.83729, 2.4805, 0.477004], + ["cyl_bessel_k", 1.83729, 2.4805, 0.112671], + ["cyl_neumann", 1.83729, 2.4805, -0.3184], + ["sph_bessel", 5, 2.4805, 0.00710255], + ["sph_neumann", 5, 2.4805, -5.83239], + ["cyl_bessel_i", -7.87681, 4.09759, -0.914328], + ["cyl_bessel_j", -7.87681, 4.09759, -3.18184], + ["cyl_bessel_k", -7.87681, 4.09759, 3.86585], + ["cyl_neumann", -7.87681, 4.09759, -7.82173], + ["sph_bessel", 8, 4.09759, 0.00146813], + ["sph_neumann", 8, 4.09759, -11.2088], + ["cyl_bessel_i", -8, -2.22243, 6.60755e-5], + ["cyl_bessel_j", -8, -2.22243, 5.02177e-5], + ["cyl_bessel_k", -7.50347, 2.22243, 354.234], + ["cyl_neumann", -7.50347, 2.22243, -3.59624], + ["sph_bessel", 0, 2.22243, 0.357761], + ["sph_neumann", 0, 2.22243, 0.272892], + ["cyl_bessel_i", 0.835801, 1.81454, 1.48687], + ["cyl_bessel_j", 0.835801, 1.81454, 0.599555], + ["cyl_bessel_k", 0.835801, 1.81454, 0.167517], + ["cyl_neumann", 0.835801, 1.81454, -0.103939], + ["sph_bessel", 1, 1.81454, 0.42774], + ["sph_neumann", 1, 1.81454, -0.461519], + ["cyl_bessel_i", -1, -8.35717, -560.474], + ["cyl_bessel_j", -1, -8.35717, 0.268956], + ["cyl_bessel_k", -0.10039, 8.35717, 0.000100382], + ["cyl_neumann", -0.10039, 8.35717, 0.273118], + ["sph_bessel", 6, 8.35717, 0.147167], + ["sph_neumann", 6, 8.35717, -0.00218726], + ["cyl_bessel_i", 8, -6.67288, 1.22706], + ["cyl_bessel_j", 8, -6.67288, 0.10095], + ["cyl_bessel_k", 8.50456, 6.67288, 0.0648458], + ["cyl_neumann", 8.50456, 6.67288, -0.931831], + ["sph_bessel", 4, 6.67288, 0.161166], + ["sph_neumann", 4, 6.67288, 0.0593303], + ["cyl_bessel_i", -8, -3.48179, 0.00291432], + ["cyl_bessel_j", -8, -3.48179, 0.00148539], + ["cyl_bessel_k", -7.1014, 3.48179, 5.28111], + ["cyl_neumann", -7.1014, 3.48179, 8.69768], + ["sph_bessel", 9, 3.48179, 8.57394e-5], + ["sph_neumann", 9, 3.48179, -189.725], + ["cyl_bessel_i", -1, -9.16822, -1209.58], + ["cyl_bessel_j", -1, -9.16822, 0.222404], + ["cyl_bessel_k", -0.328978, 9.16822, 4.28565e-5], + ["cyl_neumann", -0.328978, 9.16822, 0.133812], + ["sph_bessel", 9, 9.16822, 0.0752846], + ["sph_neumann", 9, 9.16822, -0.17498], + ["cyl_bessel_i", -4, -3.68293, 0.912407], + ["cyl_bessel_j", -4, -3.68293, 0.232636], + ["cyl_bessel_k", -3.62997, 3.68293, 0.0735086], + ["cyl_neumann", -3.62997, 3.68293, -0.467728], + ["sph_bessel", 5, 3.68293, 0.0379293], + ["sph_neumann", 5, 3.68293, -0.908662], + ["cyl_bessel_i", 6.11362, 7.53252, 22.5449], + ["cyl_bessel_j", 6.11362, 7.53252, 0.351615], + ["cyl_bessel_k", 6.11362, 7.53252, 0.00228427], + ["cyl_neumann", 6.11362, 7.53252, -0.101001], + ["sph_bessel", 5, 7.53252, 0.155321], + ["sph_neumann", 5, 7.53252, 0.0262202], + ["cyl_bessel_i", 4.18229, 5.20598, 5.69618], + ["cyl_bessel_j", 4.18229, 5.20598, 0.386537], + ["cyl_bessel_k", 4.18229, 5.20598, 0.0131229], + ["cyl_neumann", 4.18229, 5.20598, -0.186398], + ["sph_bessel", 9, 5.20598, 0.00220675], + ["sph_neumann", 9, 5.20598, -5.51105], + ["cyl_bessel_i", -6.85055, 0.503723, 983143], + ["cyl_bessel_j", -6.85055, 0.503723, 1.0047e6], + ["cyl_bessel_k", -6.85055, 0.503723, 3.41324e6], + ["cyl_neumann", -6.85055, 0.503723, 1.98028e6], + ["sph_bessel", 10, 0.503723, 7.60749e-14], + ["sph_neumann", 10, 0.503723, -1.24409e12], + ["cyl_bessel_i", 5.99273, 2.32385, 0.00418837], + ["cyl_bessel_j", 5.99273, 2.32385, 0.00284636], + ["cyl_bessel_k", 5.99273, 2.32385, 18.5485], + ["cyl_neumann", 5.99273, 2.32385, -20.3284], + ["sph_bessel", 9, 2.32385, 2.65254e-6], + ["sph_neumann", 9, 2.32385, -8809.56], + ["cyl_bessel_i", 2.54528, 5.31053, 18.5502], + ["cyl_bessel_j", 2.54528, 5.31053, 0.16231], + ["cyl_bessel_k", 2.54528, 5.31053, 0.00457722], + ["cyl_neumann", 2.54528, 5.31053, 0.329043], + ["sph_bessel", 2, 5.31053, 0.0791575], + ["sph_neumann", 2, 5.31053, 0.182664], + ["cyl_bessel_i", 7.54013, 2.83657, 0.00115315], + ["cyl_bessel_j", 7.54013, 2.83657, 0.000719823], + ["cyl_bessel_k", 7.54013, 2.83657, 53.7789], + ["cyl_neumann", 7.54013, 2.83657, -63.4366], + ["sph_bessel", 9, 2.83657, 1.49682e-5], + ["sph_neumann", 9, 2.83657, -1299.75], + ["cyl_bessel_i", 3.71167, 3.02275, 0.470382], + ["cyl_bessel_j", 3.71167, 3.02275, 0.177665], + ["cyl_bessel_k", 3.71167, 3.02275, 0.221126], + ["cyl_neumann", 3.71167, 3.02275, -0.770773], + ["sph_bessel", 9, 3.02275, 2.58322e-5], + ["sph_neumann", 9, 3.02275, -711.569], + ["cyl_bessel_i", -9.50312, 8.67655, 5.31574], + ["cyl_bessel_j", -9.50312, 8.67655, -0.517948], + ["cyl_bessel_k", -9.50312, 8.67655, 0.0072988], + ["cyl_neumann", -9.50312, 8.67655, -0.144548], + ["sph_bessel", 2, 8.67655, -0.0460811], + ["sph_neumann", 2, 8.67655, -0.108214], + ["cyl_bessel_i", -1, -7.62485, -280.716], + ["cyl_bessel_j", -1, -7.62485, 0.164887], + ["cyl_bessel_k", -0.0301369, 7.62485, 0.000218189], + ["cyl_neumann", -0.0301369, 7.62485, 0.159972], + ["sph_bessel", 7, 7.62485, 0.109295], + ["sph_neumann", 7, 7.62485, -0.168748], + ["cyl_bessel_i", 1.57277, 7.15062, 160.884], + ["cyl_bessel_j", 1.57277, 7.15062, -0.185673], + ["cyl_bessel_k", 1.57277, 7.15062, 0.000425206], + ["cyl_neumann", 1.57277, 7.15062, -0.237692], + ["sph_bessel", 6, 7.15062, 0.142706], + ["sph_neumann", 6, 7.15062, -0.129577], + ["cyl_bessel_i", -10, -8.93127, 4.74078], + ["cyl_bessel_j", -10, -8.93127, 0.119498], + ["cyl_bessel_k", -9.12714, 8.93127, 0.00357327], + ["cyl_neumann", -9.12714, 8.93127, 0.296753], + ["sph_bessel", 6, 8.93127, 0.123788], + ["sph_neumann", 6, 8.93127, 0.0491768], + ["cyl_bessel_i", 4, -0.171541, 2.25829e-6], + ["cyl_bessel_j", 4, -0.171541, 2.25166e-6], + ["cyl_bessel_k", 4.96692, 0.171541, 2.26371e6], + ["cyl_neumann", 4.96692, 0.171541, -1.44648e6], + ["sph_bessel", 2, 0.171541, 0.00195764], + ["sph_neumann", 2, 0.171541, -597.252], + ["cyl_bessel_i", -4, -0.603319, 0.000351356], + ["cyl_bessel_j", -4, -0.603319, 0.000338797], + ["cyl_bessel_k", -3.02084, 0.603319, 36.4334], + ["cyl_neumann", -3.02084, 0.603319, 25.3317], + ["sph_bessel", 2, 0.603319, 0.0236417], + ["sph_neumann", 2, 0.603319, -14.5606], + ["cyl_bessel_i", -7.53551, 8.00183, 12.7991], + ["cyl_bessel_j", -7.53551, 8.00183, -0.273256], + ["cyl_bessel_k", -7.53551, 8.00183, 0.00355087], + ["cyl_neumann", -7.53551, 8.00183, -0.304828], + ["sph_bessel", 4, 8.00183, 0.0206679], + ["sph_neumann", 4, 8.00183, 0.135086], + ["cyl_bessel_i", 9, -3.63952, -0.00083579], + ["cyl_bessel_j", 9, -3.63952, -0.000430825], + ["cyl_bessel_k", 9.08811, 3.63952, 70.8721], + ["cyl_neumann", 9.08811, 3.63952, -102.55], + ["sph_bessel", 10, 3.63952, 2.21627e-5], + ["sph_neumann", 10, 3.63952, -629.909], + ["cyl_bessel_i", -2.98486, 8.23219, 300.276], + ["cyl_bessel_j", -2.98486, 8.23219, 0.286154], + ["cyl_bessel_k", -2.98486, 8.23219, 0.000190268], + ["cyl_neumann", -2.98486, 8.23219, 0.0276635], + ["sph_bessel", 5, 8.23219, 0.108119], + ["sph_neumann", 5, 8.23219, 0.0878742], + ["cyl_bessel_i", 3, -9.18751, -780.476], + ["cyl_bessel_j", 3, -9.18751, 0.140255], + ["cyl_bessel_k", 3.51304, 9.18751, 7.86307e-5], + ["cyl_neumann", 3.51304, 9.18751, -0.107435], + ["sph_bessel", 7, 9.18751, 0.136689], + ["sph_neumann", 7, 9.18751, -0.0234403], + ["cyl_bessel_i", -7, -3.50398, -0.01464], + ["cyl_bessel_j", -7, -3.50398, 0.00679068], + ["cyl_bessel_k", -6.50483, 3.50398, 2.22984], + ["cyl_neumann", -6.50483, 3.50398, 0.0801367], + ["sph_bessel", 8, 3.50398, 0.00047492], + ["sph_neumann", 8, 3.50398, -38.8885], + ["cyl_bessel_i", 0, -0.0553816, 1.00077], + ["cyl_bessel_j", 0, -0.0553816, 0.999233], + ["cyl_bessel_k", 0.721373, 0.0553816, 8.26596], + ["cyl_neumann", 0.721373, 0.0553816, -5.40892], + ["sph_bessel", 4, 0.0553816, 9.95335e-9], + ["sph_neumann", 4, 0.0553816, -2.01585e8], + ["cyl_bessel_i", 2.74527, 2.24474, 0.432128], + ["cyl_bessel_j", 2.74527, 2.24474, 0.220114], + ["cyl_bessel_k", 2.74527, 2.24474, 0.323844], + ["cyl_neumann", 2.74527, 2.24474, -0.790245], + ["sph_bessel", 7, 2.24474, 0.000122019], + ["sph_neumann", 7, 2.24474, -255.379], + ["cyl_bessel_i", -5, -9.57989, -493.19], + ["cyl_bessel_j", -5, -9.57989, -0.175594], + ["cyl_bessel_k", -4.42218, 9.57989, 7.21386e-5], + ["cyl_neumann", -4.42218, 9.57989, -0.237152], + ["sph_bessel", 7, 9.57989, 0.129064], + ["sph_neumann", 7, 9.57989, 0.0101783], + ["cyl_bessel_i", -8.31407, 6.48532, 0.690493], + ["cyl_bessel_j", -8.31407, 6.48532, 0.827459], + ["cyl_bessel_k", -8.31407, 6.48532, 0.0726749], + ["cyl_neumann", -8.31407, 6.48532, -0.46665], + ["sph_bessel", 2, 6.48532, -0.0986238], + ["sph_neumann", 2, 6.48532, 0.125961], + ["cyl_bessel_i", -9, -1.31369, -6.54795e-8], + ["cyl_bessel_j", -9, -1.31369, 6.00662e-8], + ["cyl_bessel_k", -8.08732, 1.31369, 84719.1], + ["cyl_neumann", -8.08732, 1.31369, -58639.9], + ["sph_bessel", 9, 1.31369, 1.70804e-8], + ["sph_neumann", 9, 1.31369, -2.36863e6], + ["cyl_bessel_i", -7.93764, 0.225615, -9.1515e9], + ["cyl_bessel_j", -7.93764, 0.225615, -9.18514e9], + ["cyl_bessel_k", -7.93764, 0.225615, 7.38453e10], + ["cyl_neumann", -7.93764, 0.225615, -4.62815e10], + ["sph_bessel", 1, 0.225615, 0.0748229], + ["sph_neumann", 1, 0.225615, -20.1392], + ["cyl_bessel_i", 3, -7.98514, -232.549], + ["cyl_bessel_j", 3, -7.98514, 0.291048], + ["cyl_bessel_k", 3.88922, 7.98514, 0.000359339], + ["cyl_neumann", 3.88922, 7.98514, 0.26957], + ["sph_bessel", 8, 7.98514, 0.0755992], + ["sph_neumann", 8, 7.98514, -0.211928], + ["cyl_bessel_i", 4, -6.31303, 23.7474], + ["cyl_bessel_j", 4, -6.31303, 0.31048], + ["cyl_bessel_k", 4.03783, 6.31303, 0.00287623], + ["cyl_neumann", 4.03783, 6.31303, 0.164831], + ["sph_bessel", 2, 6.31303, -0.0796118], + ["sph_neumann", 2, 6.31303, 0.144167], + ["cyl_bessel_i", -0.861386, 1.31593, 1.00966], + ["cyl_bessel_j", -0.861386, 1.31593, -0.332739], + ["cyl_bessel_k", -0.861386, 1.31593, 0.337834], + ["cyl_neumann", -0.861386, 1.31593, 0.650858], + ["sph_bessel", 9, 1.31593, 1.7342e-8], + ["sph_neumann", 9, 1.31593, -2.329e6], + ["cyl_bessel_i", -6, -6.07757, 3.73205], + ["cyl_bessel_j", -6, -6.07757, 0.25479], + ["cyl_bessel_k", -5.12254, 6.07757, 0.00789359], + ["cyl_neumann", -5.12254, 6.07757, 0.0599454], + ["sph_bessel", 2, 6.07757, -0.0486437], + ["sph_neumann", 2, 6.07757, 0.164574], + ["cyl_bessel_i", -9.5789, 9.68195, 20.6139], + ["cyl_bessel_j", -9.5789, 9.68195, -0.2836], + ["cyl_bessel_k", -9.5789, 9.68195, 0.00177993], + ["cyl_neumann", -9.5789, 9.68195, -0.298044], + ["sph_bessel", 6, 9.68195, 0.0713991], + ["sph_neumann", 6, 9.68195, 0.095153], + ["cyl_bessel_i", 6.50983, 0.124883, 7.55974e-12], + ["cyl_bessel_j", 6.50983, 0.124883, 7.5519e-12], + ["cyl_bessel_k", 6.50983, 0.124883, 1.01581e10], + ["cyl_neumann", 6.50983, 0.124883, -6.47599e9], + ["sph_bessel", 3, 0.124883, 1.85328e-5], + ["sph_neumann", 3, 0.124883, -61767.6], + ["beta", 5.43738, 1.71319, 0.0451108], + ["beta", 2.89448, 0.0497214, 18.7339], + ["beta", 7.46809, 6.23994, 0.00010934], + ["beta", 5.22812, 3.45574, 0.00522637], + ["beta", 6.36728, 2.03572, 0.0201107], + ["beta", 4.31352, 1.88203, 0.051268], + ["beta", 7.08725, 9.90967, 1.21142e-5], + ["beta", 5.32322, 8.74347, 0.000124601], + ["beta", 9.34825, 9.87443, 1.90788e-6], + ["beta", 7.24796, 2.49304, 0.00749075], + ["beta", 9.83016, 2.51868, 0.00354993], + ["beta", 8.44675, 4.53855, 0.00033414], + ["beta", 8.9874, 6.37067, 3.93316e-5], + ["beta", 7.92248, 5.69563, 0.000134021], + ["beta", 0.8492, 9.99829, 0.158563], + ["beta", 7.75038, 7.31423, 3.85812e-5], + ["beta", 1.42852, 5.46504, 0.0742643], + ["beta", 8.88054, 9.47825, 3.56474e-6], + ["beta", 9.06027, 4.52497, 0.000259517], + ["beta", 5.47452, 6.58204, 0.000365749], + ["beta", 8.24053, 3.51883, 0.00125396], + ["beta", 0.189918, 3.70955, 3.86156], + ["beta", 0.00782859, 6.02956, 125.474], + ["beta", 7.49258, 2.01902, 0.0151955], + ["beta", 2.57324, 6.21319, 0.00949151], + ["beta", 1.01981, 2.19734, 0.441227], + ["beta", 9.71832, 2.07482, 0.00828162], + ["beta", 3.4171, 7.13227, 0.00220841], + ["beta", 7.20966, 4.86089, 0.000439923], + ["beta", 5.39944, 6.61502, 0.000381674], + ["beta", 7.34528, 7.90898, 3.37583e-5], + ["beta", 6.71504, 4.85612, 0.00058301], + ["beta", 4.56017, 5.37249, 0.00173169], + ["beta", 5.87835, 8.49994, 8.17672e-5], + ["beta", 6.38919, 6.37431, 0.000205797], + ["beta", 6.08356, 2.01189, 0.0227678], + ["beta", 4.40998, 7.34242, 0.000648347], + ["beta", 9.75145, 7.56476, 8.6738e-6], + ["beta", 7.94025, 6.06033, 9.53499e-5], + ["beta", 5.61042, 9.205, 7.3666e-5], + ["beta", 8.68901, 0.569803, 0.462354], + ["beta", 9.29875, 3.9614, 0.000474023], + ["beta", 4.27731, 4.60095, 0.0037018], + ["beta", 9.71905, 8.49655, 4.08561e-6], + ["beta", 6.42907, 5.29782, 0.000468284], + ["beta", 7.96906, 7.14175, 3.79639e-5], + ["beta", 5.65342, 7.53013, 0.00017481], + ["beta", 4.68445, 6.19567, 0.00092629], + ["beta", 3.70331, 5.39251, 0.0037256], + ["beta", 9.94457, 1.04385, 0.0885876], + ["beta", 7.58347, 1.07694, 0.107863], + ["beta", 3.64423, 6.47693, 0.0022638], + ["beta", 4.2543, 9.6481, 0.00028521], + ["beta", 9.87066, 8.96982, 2.55068e-6], + ["beta", 6.57817, 4.91419, 0.000598654], + ["beta", 8.7025, 2.23292, 0.00771546], + ["beta", 5.80084, 9.36054, 5.60965e-5], + ["beta", 0.481414, 5.59908, 0.820973], + ["beta", 5.43028, 7.71843, 0.000192619], + ["beta", 7.10064, 1.42663, 0.0519003], + ["beta", 2.53228, 9.33181, 0.00391778], + ["beta", 9.33454, 2.20476, 0.00701603], + ["beta", 8.40432, 7.61149, 1.96092e-5], + ["beta", 0.904159, 0.402794, 2.61726], + ["beta", 7.75319, 9.4034, 9.14529e-6], + ["beta", 2.74711, 5.19757, 0.0115493], + ["beta", 9.56415, 2.02418, 0.00943596], + ["beta", 9.44011, 0.612901, 0.373523], + ["beta", 2.54554, 0.201872, 3.88965], + ["beta", 0.852063, 9.0165, 0.171701], + ["beta", 9.82615, 1.6511, 0.0196327], + ["beta", 2.02192, 2.24728, 0.134364], + ["beta", 1.69071, 6.3591, 0.0364494], + ["beta", 4.53191, 2.19808, 0.0306486], + ["beta", 7.00224, 1.93562, 0.0199561], + ["beta", 5.75182, 4.99803, 0.000935619], + ["beta", 0.322443, 7.15128, 1.4936], + ["beta", 2.00733, 4.0057, 0.0494057], + ["beta", 8.47945, 6.73179, 3.83568e-5], + ["beta", 1.48589, 9.13783, 0.0318485], + ["beta", 7.08407, 3.65468, 0.00169417], + ["beta", 7.70133, 4.12746, 0.000745045], + ["beta", 1.44993, 9.74869, 0.0315709], + ["beta", 3.24803, 2.9477, 0.0288503], + ["beta", 3.58225, 2.59873, 0.0317478], + ["beta", 5.35169, 1.53762, 0.062626], + ["beta", 2.92817, 6.12332, 0.0061714], + ["beta", 7.91203, 8.74139, 1.23663e-5], + ["beta", 8.30012, 8.84477, 8.55546e-6], + ["beta", 0.600091, 2.38175, 0.929292], + ["beta", 0.253569, 5.78954, 2.32641], + ["beta", 0.117011, 3.06178, 7.20817], + ["beta", 4.3661, 8.69075, 0.000366092], + ["beta", 2.19768, 1.77675, 0.175246], + ["beta", 0.239327, 2.98162, 3.01619], + ["beta", 5.17838, 8.93513, 0.000132104], + ["beta", 0.874823, 6.05102, 0.227633], + ["beta", 1.04186, 0.887291, 1.08512], + ["beta", 5.76291, 9.33735, 5.89872e-5], + ["beta", 1.26049, 4.60205, 0.127642], + ["ellint_1", -0.984468, 0.295747, 0.300014], + ["ellint_2", -0.984468, 0.295747, 0.291589], + ["ellint_3", -0.984468, 9.46851, 0.295747, 0.493196], + ["ellint_1", 0.838026, 0.144616, 0.144971], + ["ellint_2", 0.838026, 0.144616, 0.144263], + ["ellint_3", 0.838026, 15.4614, 0.144616, 0.164499], + ["ellint_1", 0.545513, -1.33552, -1.43283], + ["ellint_2", 0.545513, -1.33552, -1.2485], + ["ellint_3", 0.545513, 0.614444, -1.33552, -2.11035], + ["ellint_1", -0.101389, 1.10574, 1.10756], + ["ellint_2", -0.101389, 1.10574, 1.10393], + ["ellint_3", -0.101389, 1.13461, 1.10574, 2.54495], + ["ellint_1", -0.46228, -0.334716, -0.336035], + ["ellint_2", -0.46228, -0.334716, -0.333405], + ["ellint_3", -0.46228, 3.71831, -0.334716, -0.397609], + ["ellint_1", -0.87414, 0.353207, 0.35892], + ["ellint_2", -0.87414, 0.353207, 0.347655], + ["ellint_3", -0.87414, 6.2976, 0.353207, 0.555621], + ["ellint_1", 0.587268, 0.176722, 0.177038], + ["ellint_2", 0.587268, 0.176722, 0.176406], + ["ellint_3", 0.587268, 7.15596, 0.176722, 0.192244], + ["ellint_1", -0.477195, -0.945677, -0.974616], + ["ellint_2", -0.477195, -0.945677, -0.918177], + ["ellint_3", -0.477195, 0.302658, -0.945677, -1.06091], + ["ellint_1", 0.0680548, 1.09223, 1.09303], + ["ellint_2", 0.0680548, 1.09223, 1.09144], + ["ellint_3", 0.0680548, 0.31128, 1.09223, 1.22052], + ["ellint_1", 0.347204, 0.825219, 0.835382], + ["ellint_2", 0.347204, 0.825219, 0.815267], + ["ellint_3", 0.347204, 1.41402, 0.825219, 1.361], + ["ellint_1", 0.6392, -0.709607, -0.733586], + ["ellint_2", 0.6392, -0.709607, -0.68698], + ["ellint_3", 0.6392, 2.0131, -0.709607, -1.36893], + ["ellint_1", -0.848038, 1.23319, 1.49455], + ["ellint_2", -0.848038, 1.23319, 1.04305], + ["ellint_3", -0.848038, 0.740237, 1.23319, 2.4358], + ["ellint_1", 0.0444439, -0.266119, -0.266126], + ["ellint_2", 0.0444439, -0.266119, -0.266113], + ["ellint_3", 0.0444439, 12.7919, -0.266119, -0.496551], + ["ellint_1", 0.261943, 1.06557, 1.07687], + ["ellint_2", 0.261943, 1.06557, 1.05446], + ["ellint_3", 0.261943, 0.352215, 1.06557, 1.21738], + ["ellint_1", 0.697384, -0.255215, -0.256563], + ["ellint_2", 0.697384, -0.255215, -0.253878], + ["ellint_3", 0.697384, 10.5985, -0.255215, -0.364698], + ["ellint_1", -0.169898, -1.47118, -1.48124], + ["ellint_2", -0.169898, -1.47118, -1.46122], + ["ellint_3", -0.169898, 0.891215, -1.47118, -3.90997], + ["ellint_1", -0.345543, 0.217188, 0.21739], + ["ellint_2", -0.345543, 0.217188, 0.216986], + ["ellint_3", -0.345543, 9.74104, 0.217188, 0.263935], + ["ellint_1", -0.666716, -0.826831, -0.868204], + ["ellint_2", -0.666716, -0.826831, -0.788805], + ["ellint_3", -0.666716, 1.33096, -0.826831, -1.36078], + ["ellint_1", 0.345407, 0.791023, 0.799959], + ["ellint_2", 0.345407, 0.791023, 0.782258], + ["ellint_3", 0.345407, 1.78301, 0.791023, 1.66329], + ["ellint_1", -0.424951, -0.333977, -0.335083], + ["ellint_2", -0.424951, -0.333977, -0.332877], + ["ellint_3", -0.424951, 1.46922, -0.333977, -0.354965], + ["ellint_1", 0.455995, 0.91142, 0.93512], + ["ellint_2", 0.455995, 0.91142, 0.888731], + ["ellint_3", 0.455995, 0.306343, 0.91142, 1.01321], + ["ellint_1", -0.209138, 0.309056, 0.309267], + ["ellint_2", -0.209138, 0.309056, 0.308844], + ["ellint_3", -0.209138, 7.61937, 0.309056, 0.451785], + ["ellint_1", 0.530719, 0.313064, 0.314494], + ["ellint_2", 0.530719, 0.313064, 0.311646], + ["ellint_3", 0.530719, 0.188901, 0.313064, 0.316425], + ["ellint_1", -0.0481149, -0.497058, -0.497103], + ["ellint_2", -0.0481149, -0.497058, -0.497013], + ["ellint_3", -0.0481149, 2.97598, -0.497058, -0.713138], + ["ellint_1", -0.0445318, 1.32618, 1.32672], + ["ellint_2", -0.0445318, 1.32618, 1.32564], + ["ellint_3", -0.0445318, 0.980876, 1.32618, 3.66074], + ["ellint_1", -0.955478, -1.09603, -1.36441], + ["ellint_2", -0.955478, -1.09603, -0.911687], + ["ellint_3", -0.955478, 1.19138, -1.09603, -4.25377], + ["ellint_1", 0.0239343, -1.10623, -1.10633], + ["ellint_2", 0.0239343, -1.10623, -1.10613], + ["ellint_3", 0.0239343, 1.08475, -1.10623, -2.28057], + ["ellint_1", 0.35651, -0.346231, -0.347095], + ["ellint_2", 0.35651, -0.346231, -0.34537], + ["ellint_3", 0.35651, 3.86336, -0.346231, -0.420596], + ["ellint_1", -0.78602, -0.523364, -0.538426], + ["ellint_2", -0.78602, -0.523364, -0.509041], + ["ellint_3", -0.78602, 3.3039, -0.523364, -0.932434], + ["ellint_1", -0.588546, -0.793881, -0.821694], + ["ellint_2", -0.588546, -0.793881, -0.767676], + ["ellint_3", -0.588546, 0.597188, -0.793881, -0.937944], + ["ellint_1", -0.209187, 1.01376, 1.02004], + ["ellint_2", -0.209187, 1.01376, 1.00755], + ["ellint_3", -0.209187, 0.852227, 1.01376, 1.44958], + ["ellint_1", 0.072815, -1.40598, -1.40763], + ["ellint_2", 0.072815, -1.40598, -1.40433], + ["ellint_3", 0.072815, 0.551379, -1.40598, -1.98458], + ["ellint_1", -0.458443, 0.286873, 0.287692], + ["ellint_2", -0.458443, 0.286873, 0.286057], + ["ellint_3", -0.458443, 10.1671, 0.286873, 0.476763], + ["ellint_1", -0.574771, -0.104067, -0.104129], + ["ellint_2", -0.574771, -0.104067, -0.104005], + ["ellint_3", -0.574771, 87.0271, -0.104067, -0.223546], + ["ellint_1", 0.864387, 1.34285, 1.70889], + ["ellint_2", 0.864387, 1.34285, 1.09538], + ["ellint_3", 0.864387, 0.0473684, 1.34285, 1.74912], + ["ellint_1", -0.343869, -0.280505, -0.280935], + ["ellint_2", -0.343869, -0.280505, -0.280077], + ["ellint_3", -0.343869, 8.78366, -0.280505, -0.398367], + ["ellint_1", -0.692352, 0.156082, 0.156386], + ["ellint_2", -0.692352, 0.156082, 0.155779], + ["ellint_3", -0.692352, 34.1786, 0.156082, 0.262384], + ["ellint_1", -0.683543, 1.27797, 1.43087], + ["ellint_2", -0.683543, 1.27797, 1.15062], + ["ellint_3", -0.683543, 0.752585, 1.27797, 2.39059], + ["ellint_1", 0.338052, -1.337, -1.37067], + ["ellint_2", 0.338052, -1.337, -1.30462], + ["ellint_3", 0.338052, 0.714809, -1.337, -2.22571], + ["ellint_1", -0.406244, -1.09029, -1.1203], + ["ellint_2", -0.406244, -1.09029, -1.06159], + ["ellint_3", -0.406244, 0.368515, -1.09029, -1.28352], + ["ellint_1", -0.0428997, 1.05212, 1.05241], + ["ellint_2", -0.0428997, 1.05212, 1.05184], + ["ellint_3", -0.0428997, 1.16408, 1.05212, 2.18933], + ["ellint_1", 0.9268, 0.43004, 0.441831], + ["ellint_2", 0.9268, 0.43004, 0.418806], + ["ellint_3", 0.9268, 1.2522, 0.43004, 0.48072], + ["ellint_1", 0.708416, 0.685444, 0.712568], + ["ellint_2", 0.708416, 0.685444, 0.660105], + ["ellint_3", 0.708416, 2.12802, 0.685444, 1.32437], + ["ellint_1", -0.0241848, -0.832604, -0.832653], + ["ellint_2", -0.0241848, -0.832604, -0.832555], + ["ellint_3", -0.0241848, 0.600834, -0.832604, -0.960801], + ["ellint_1", -0.378848, -1.18504, -1.21705], + ["ellint_2", -0.378848, -1.18504, -1.15438], + ["ellint_3", -0.378848, 0.33314, -1.18504, -1.39835], + ["ellint_1", 0.353249, 1.47103, 1.51695], + ["ellint_2", 0.353249, 1.47103, 1.42722], + ["ellint_3", 0.353249, 0.514756, 1.47103, 2.12571], + ["ellint_1", -0.567713, -1.2609, -1.35348], + ["ellint_2", -0.567713, -1.2609, -1.17832], + ["ellint_3", -0.567713, 0.189859, -1.2609, -1.47081], + ["ellint_1", 0.528307, -0.924118, -0.957992], + ["ellint_2", 0.528307, -0.924118, -0.892254], + ["ellint_3", 0.528307, 0.566041, -0.924118, -1.13382], + ["ellint_1", -0.600292, 0.133885, 0.134029], + ["ellint_2", -0.600292, 0.133885, 0.133741], + ["ellint_3", -0.600292, 22.1983, 0.133885, 0.157709], + ["ellint_1", -0.66083, -0.0102686, -0.0102686], + ["ellint_2", -0.66083, -0.0102686, -0.0102685], + ["ellint_3", -0.66083, 3893.99, -0.0102686, -0.012171], + ["ellint_1", 0.3211, 1.56607, 1.60883], + ["ellint_2", 0.3211, 1.56607, 1.52501], + ["ellint_3", 0.3211, 0.436156, 1.56607, 2.14868], + ["ellint_1", 0.172887, 0.642177, 0.643398], + ["ellint_2", 0.172887, 0.642177, 0.64096], + ["ellint_3", 0.172887, 0.885503, 0.642177, 0.734085], + ["ellint_1", 0.841379, -0.757802, -0.812603], + ["ellint_2", 0.841379, -0.757802, -0.709311], + ["ellint_3", 0.841379, 2.06607, -0.757802, -2.46395], + ["ellint_1", -0.923881, 0.775936, 0.850552], + ["ellint_2", -0.923881, 0.775936, 0.712442], + ["ellint_3", -0.923881, 0.609328, 0.775936, 0.97359], + ["ellint_1", 0.454701, 0.539973, 0.545223], + ["ellint_2", 0.454701, 0.539973, 0.534812], + ["ellint_3", 0.454701, 1.78819, 0.539973, 0.675698], + ["ellint_1", -0.356787, -0.877363, -0.8901], + ["ellint_2", -0.356787, -0.877363, -0.864936], + ["ellint_3", -0.356787, 0.693058, -0.877363, -1.0788], + ["ellint_1", -0.32632, -0.934312, -0.946876], + ["ellint_2", -0.32632, -0.934312, -0.922027], + ["ellint_3", -0.32632, 1.00688, -0.934312, -1.38203], + ["ellint_1", 0.064671, 0.293766, 0.293783], + ["ellint_2", 0.064671, 0.293766, 0.293748], + ["ellint_3", 0.064671, 2.40198, 0.293766, 0.316574], + ["ellint_1", 0.266846, -0.411852, -0.412657], + ["ellint_2", 0.266846, -0.411852, -0.411049], + ["ellint_3", 0.266846, 3.73669, -0.411852, -0.553346], + ["ellint_1", -0.145555, 0.235233, 0.235279], + ["ellint_2", -0.145555, 0.235233, 0.235188], + ["ellint_3", -0.145555, 11.8295, 0.235233, 0.324624], + ["ellint_1", -0.32953, 0.394782, 0.395869], + ["ellint_2", -0.32953, 0.394782, 0.3937], + ["ellint_3", -0.32953, 6.08534, 0.394782, 0.772534], + ["ellint_1", 0.692478, 0.214558, 0.215348], + ["ellint_2", 0.692478, 0.214558, 0.213773], + ["ellint_3", 0.692478, 7.36228, 0.214558, 0.245962], + ["ellint_1", 0.208947, -0.257717, -0.25784], + ["ellint_2", 0.208947, -0.257717, -0.257594], + ["ellint_3", 0.208947, 0.450186, -0.257717, -0.260422], + ["ellint_1", -0.361696, -1.51208, -1.56336], + ["ellint_2", -0.361696, -1.51208, -1.46335], + ["ellint_3", -0.361696, 0.0898474, -1.51208, -1.63695], + ["ellint_1", -0.169185, -1.44398, -1.45356], + ["ellint_2", -0.169185, -1.44398, -1.4345], + ["ellint_3", -0.169185, 0.623731, -1.44398, -2.24493], + ["ellint_1", 0.8723, -0.0660934, -0.06613], + ["ellint_2", 0.8723, -0.0660934, -0.0660568], + ["ellint_3", 0.8723, 45.3058, -0.0660934, -0.0710945], + ["ellint_1", 0.302987, 1.38791, 1.41703], + ["ellint_2", 0.302987, 1.38791, 1.35971], + ["ellint_3", 0.302987, 0.683318, 1.38791, 2.28648], + ["ellint_1", -0.550584, -0.457521, -0.462291], + ["ellint_2", -0.550584, -0.457521, -0.452838], + ["ellint_3", -0.550584, 0.792576, -0.457521, -0.48963], + ["ellint_1", -0.983507, -0.537127, -0.563947], + ["ellint_2", -0.983507, -0.537127, -0.512541], + ["ellint_3", -0.983507, 1.56132, -0.537127, -0.677294], + ["ellint_1", -0.0452787, 1.39888, 1.39951], + ["ellint_2", -0.0452787, 1.39888, 1.39825], + ["ellint_3", -0.0452787, 0.703708, 1.39888, 2.31983], + ["ellint_1", -0.868191, 1.05349, 1.22341], + ["ellint_2", -0.868191, 1.05349, 0.921796], + ["ellint_3", -0.868191, 1.26759, 1.05349, 3.85575], + ["ellint_1", -0.60511, 0.97011, 1.02277], + ["ellint_2", -0.60511, 0.97011, 0.921957], + ["ellint_3", -0.60511, 0.954422, 0.97011, 1.51374], + ["ellint_1", 0.246655, 1.17235, 1.18507], + ["ellint_2", 0.246655, 1.17235, 1.15985], + ["ellint_3", 0.246655, 0.132714, 1.17235, 1.2446], + ["ellint_1", 0.0108285, 1.20277, 1.20279], + ["ellint_2", 0.0108285, 1.20277, 1.20274], + ["ellint_3", 0.0108285, 0.546037, 1.20277, 1.55992], + ["ellint_1", -0.321756, 1.03162, 1.04751], + ["ellint_2", -0.321756, 1.03162, 1.01613], + ["ellint_3", -0.321756, 1.30547, 1.03162, 2.99911], + ["ellint_1", -0.588025, -0.816919, -0.847078], + ["ellint_2", -0.588025, -0.816919, -0.788588], + ["ellint_3", -0.588025, 0.111995, -0.816919, -0.86677], + ["ellint_1", -0.654467, 0.622566, 0.639679], + ["ellint_2", -0.654467, 0.622566, 0.60625], + ["ellint_3", -0.654467, 2.91406, 0.622566, 2.16111], + ["ellint_1", -0.352998, 0.292698, 0.293213], + ["ellint_2", -0.352998, 0.292698, 0.292186], + ["ellint_3", -0.352998, 11.2968, 0.292698, 0.638871], + ["ellint_1", 0.685451, 0.360093, 0.363754], + ["ellint_2", 0.685451, 0.360093, 0.356499], + ["ellint_3", 0.685451, 0.457362, 0.360093, 0.37107], + ["ellint_1", -0.362985, -1.4075, -1.45163], + ["ellint_2", -0.362985, -1.4075, -1.36544], + ["ellint_3", -0.362985, 0.221728, -1.4075, -1.6236], + ["ellint_1", 0.088819, -1.2442, -1.24606], + ["ellint_2", 0.088819, -1.2442, -1.24234], + ["ellint_3", 0.088819, 0.408524, -1.2442, -1.50552], + ["ellint_1", 0.429571, 0.7186, 0.729292], + ["ellint_2", 0.429571, 0.7186, 0.708178], + ["ellint_3", 0.429571, 2.00874, 0.7186, 1.39381], + ["ellint_1", 0.449173, 1.40165, 1.47142], + ["ellint_2", 0.449173, 1.40165, 1.33698], + ["ellint_3", 0.449173, 0.129547, 1.40165, 1.56634], + ["ellint_1", -0.146986, 0.23252, 0.232565], + ["ellint_2", -0.146986, 0.23252, 0.232475], + ["ellint_3", -0.146986, 6.27887, 0.23252, 0.265521], + ["ellint_1", 0.654824, 0.322014, 0.324398], + ["ellint_2", 0.654824, 0.322014, 0.319661], + ["ellint_3", 0.654824, 2.51581, 0.322014, 0.357383], + ["ellint_1", 0.664508, 0.469113, 0.4767], + ["ellint_2", 0.664508, 0.469113, 0.46174], + ["ellint_3", 0.664508, 2.24812, 0.469113, 0.585489], + ["ellint_1", -0.99102, 0.376992, 0.386076], + ["ellint_2", -0.99102, 0.376992, 0.368287], + ["ellint_3", -0.99102, 6.52945, 0.376992, 0.73545], + ["ellint_1", -0.594747, 0.484307, 0.490931], + ["ellint_2", -0.594747, 0.484307, 0.47784], + ["ellint_3", -0.594747, 3.64855, 0.484307, 0.80108], + ["ellint_1", 0.262888, 0.562882, 0.564828], + ["ellint_2", 0.262888, 0.562882, 0.560949], + ["ellint_3", 0.262888, 0.160547, 0.562882, 0.574101], + ["ellint_1", -0.720498, 1.2116, 1.3637], + ["ellint_2", -0.720498, 1.2116, 1.08634], + ["ellint_3", -0.720498, 0.434823, 1.2116, 1.68359], + ["ellint_1", 0.184134, 0.916918, 0.920635], + ["ellint_2", 0.184134, 0.916918, 0.913225], + ["ellint_3", 0.184134, 1.14477, 0.916918, 1.43915], + ["ellint_1", -0.924615, 0.111955, 0.112156], + ["ellint_2", -0.924615, 0.111955, 0.111755], + ["ellint_3", -0.924615, 35.2911, 0.111955, 0.135168], + ["ellint_1", -0.436881, 0.304278, 0.305165], + ["ellint_2", -0.436881, 0.304278, 0.303396], + ["ellint_3", -0.436881, 8.66038, 0.304278, 0.482354], + ["ellint_1", 0.577638, 0.50128, 0.508187], + ["ellint_2", 0.577638, 0.50128, 0.494538], + ["ellint_3", 0.577638, 1.39343, 0.50128, 0.579911], + ["ellint_1", -0.168812, 0.922179, 0.925347], + ["ellint_2", -0.168812, 0.922179, 0.91903], + ["ellint_3", -0.168812, 0.650574, 0.922179, 1.12482], + ["ellint_1", -0.650175, 1.49605, 1.69531], + ["ellint_2", -0.650175, 1.49605, 1.33175], + ["ellint_3", -0.650175, 0.687165, 1.49605, 3.02154], + ["ellint_1", 0.487261, 0.838223, 0.859825], + ["ellint_2", 0.487261, 0.838223, 0.817544], + ["ellint_3", 0.487261, 0.910365, 0.838223, 1.10599], + ["ellint_1", -0.385032, -0.228967, -0.229261], + ["ellint_2", -0.385032, -0.228967, -0.228673], + ["ellint_3", -0.385032, 17.1196, -0.228967, -0.424836], + ["ellint_1", 0.0401356, -0.560297, -0.560342], + ["ellint_2", 0.0401356, -0.560297, -0.560253], + ["ellint_3", 0.0401356, 0.262997, -0.560297, -0.575519], + ["ellint_1", -0.58318, -0.365545, -0.368295], + ["ellint_2", -0.58318, -0.365545, -0.362831], + ["ellint_3", -0.58318, 6.80767, -0.365545, -0.673598], + ["expint", 6.42081, 119.909], + ["expint", 7.29916, 244.946], + ["expint", -6.16651, -0.000297553], + ["expint", 5.34783, 52.0993], + ["expint", -4.35434, -0.00246704], + ["expint", -5.46984, -0.00066374], + ["expint", 8.39989, 618.86], + ["expint", -4.16127, -0.0031104], + ["expint", 5.46797, 57.0589], + ["expint", -5.09274, -0.00103001], + ["expint", -6.30229, -0.000254806], + ["expint", 3.02352, 10.0926], + ["expint", -4.89292, -0.0013023], + ["expint", -1.95257, -0.0522275], + ["expint", -7.97003, -3.89437e-5], + ["expint", -2.16842, -0.038819], + ["expint", 9.70953, 1929.15], + ["expint", 9.66245, 1850.94], + ["expint", -8.5487, -2.04865e-5], + ["expint", -9.47408, -7.39196e-6], + ["expint", 0.636429, 0.879243], + ["expint", 3.13162, 10.8552], + ["expint", -6.16569, -0.000297832], + ["expint", 2.71408, 8.18828], + ["expint", 7.21006, 227.567], + ["expint", 8.51513, 683.072], + ["expint", -4.91741, -0.0012653], + ["expint", 0.756737, 1.22633], + ["expint", 5.35794, 52.4982], + ["expint", 0.879612, 1.56702], + ["expint", -5.64625, -0.000541118], + ["expint", -5.93221, -0.000389226], + ["expint", 8.58423, 724.821], + ["expint", 7.64758, 327.343], + ["expint", 0.87062, 1.54237], + ["expint", 2.70635, 8.14541], + ["expint", 5.18295, 46.0347], + ["expint", 2.286, 6.0939], + ["expint", -3.34795, -0.00841951], + ["expint", 1.24832, 2.57635], + ["expint", 8.80597, 877.409], + ["expint", 0.536002, 0.570919], + ["expint", 7.61674, 319.004], + ["expint", -2.32002, -0.0316419], + ["expint", -5.4647, -0.000667709], + ["expint", -2.33373, -0.0310671], + ["expint", 8.82282, 890.272], + ["expint", -0.995415, -0.221079], + ["expint", -7.81578, -4.62501e-5], + ["expint", -6.65382, -0.000170828], + ["expint", -8.04988, -3.56315e-5], + ["expint", -8.01814, -3.69127e-5], + ["expint", -2.60365, -0.0217462], + ["expint", -3.73007, -0.00525066], + ["expint", 1.67715, 3.84775], + ["expint", 6.14644, 96.4634], + ["expint", -1.21068, -0.155753], + ["expint", 2.21571, 5.79732], + ["expint", -9.29547, -8.99315e-6], + ["expint", 5.66591, 66.3726], + ["expint", -2.46589, -0.0260621], + ["expint", -7.71188, -5.19385e-5], + ["expint", 1.02303, 1.95772], + ["expint", -5.33049, -0.000780403], + ["expint", 9.39134, 1459.41], + ["expint", -8.62532, -1.88218e-5], + ["expint", -9.03558, -1.1969e-5], + ["expint", 7.42167, 271.132], + ["expint", 4.98729, 39.81], + ["expint", -5.6136, -0.000561933], + ["expint", 4.01807, 19.8791], + ["expint", -4.47311, -0.00214089], + ["expint", 3.9668, 19.1833], + ["expint", 3.40354, 13.0434], + ["expint", -8.12399, -3.28125e-5], + ["expint", 1.42712, 3.08607], + ["expint", 3.78362, 16.9033], + ["expint", 2.29628, 6.13829], + ["expint", -4.29467, -0.00264978], + ["expint", -8.68338, -1.76518e-5], + ["expint", -3.98148, -0.00386512], + ["expint", -2.69247, -0.0193704], + ["expint", 1.48985, 3.27103], + ["expint", -7.68035, -5.38012e-5], + ["expint", -2.8383, -0.0160447], + ["expint", -3.47816, -0.00716122], + ["expint", -5.49697, -0.000643179], + ["expint", -8.29695, -2.70779e-5], + ["expint", 0.147757, -1.18157], + ["expint", 0.192795, -0.866409], + ["expint", -1.71198, -0.073379], + ["expint", 3.66991, 15.6353], + ["expint", -1.57235, -0.0898777], + ["expint", 9.81442, 2115.75], + ["expint", 0.306404, -0.274066], + ["expint", -2.04623, -0.0458783], + ["expint", 9.47317, 1567.75], + ["expint", 6.41657, 119.504], + ["expint", 1.96594, 4.82947], + ["expint", 4.8351, 35.599], + ["hermite", 7, -2.87502, -18842], + ["hermite", 6, -5.7792, 1.87293e6], + ["hermite", 8, 5.73186, 1.85235e8], + ["hermite", 8, 8.58706, 6.20341e9], + ["hermite", 3, -5.20605, -1066.32], + ["hermite", 0, -7.55584, 1], + ["hermite", 5, 9.69993, 2.60298e6], + ["hermite", 2, -6.64268, 174.501], + ["hermite", 9, 7.28107, 2.04074e10], + ["hermite", 0, -3.12747, 1], + ["hermite", 6, 2.78716, 6509.18], + ["hermite", 3, 6.78207, 2414.22], + ["hermite", 1, -4.14027, -8.28054], + ["hermite", 4, 1.62221, -3.5129], + ["hermite", 10, -1.44516, -85818.9], + ["hermite", 8, 7.37135, 1.69558e9], + ["hermite", 7, -1.13316, -781.245], + ["hermite", 7, 0.600943, -382.107], + ["hermite", 7, -9.9307, -1.09265e9], + ["hermite", 8, -6.77008, 8.12298e8], + ["hermite", 8, -8.95559, 8.82881e9], + ["hermite", 5, 2.94212, 3332.56], + ["hermite", 6, 4.78752, 534846], + ["hermite", 4, -4.09829, 3719.49], + ["hermite", 4, 5.1752, 10203.4], + ["hermite", 9, 9.96753, 4.11825e11], + ["hermite", 6, 8.19934, 1.73258e7], + ["hermite", 3, -3.80541, -395.19], + ["hermite", 0, 4.2125, 1], + ["hermite", 1, 9.16103, 18.3221], + ["hermite", 1, -2.81023, -5.62046], + ["hermite", 2, 0.646366, -0.328846], + ["hermite", 3, 9.85378, 7535.94], + ["hermite", 2, -2.14577, 16.4172], + ["hermite", 5, 9.22846, 2.01724e6], + ["hermite", 1, 4.51682, 9.03364], + ["hermite", 2, -0.0417216, -1.99304], + ["hermite", 5, 5.07386, 87316.4], + ["hermite", 2, 4.00203, 62.065], + ["hermite", 5, -3.11819, -4956.48], + ["hermite", 1, 8.56112, 17.1222], + ["hermite", 6, -7.46692, 9.64041e6], + ["hermite", 2, 3.2907, 41.3147], + ["hermite", 1, -4.3501, -8.7002], + ["hermite", 5, -1.24329, 63.2362], + ["hermite", 4, -8.6733, 86944.5], + ["hermite", 8, 5.82639, 2.14794e8], + ["hermite", 6, 5.65209, 1.61959e6], + ["hermite", 1, 0.945586, 1.89117], + ["hermite", 10, 8.14402, 9.13729e11], + ["hermite", 2, 3.67905, 52.1416], + ["hermite", 10, 0.872528, 29975.5], + ["hermite", 10, 7.18639, 2.3345e11], + ["hermite", 4, 1.90856, 49.4522], + ["hermite", 2, 0.0426016, -1.99274], + ["hermite", 5, -9.32589, -2.1287e6], + ["hermite", 3, -8.01612, -4024.61], + ["hermite", 8, -7.24918, 1.46862e9], + ["hermite", 5, 0.641412, 38.2222], + ["hermite", 0, 1.20807, 1], + ["hermite", 9, -0.799029, 3064.82], + ["hermite", 5, 6.92362, 456844], + ["hermite", 3, 2.80701, 143.254], + ["hermite", 0, -8.31758, 1], + ["hermite", 2, 0.178113, -1.8731], + ["hermite", 6, -7.16708, 7.44463e6], + ["hermite", 4, 8.47694, 79181.3], + ["hermite", 4, 4.82454, 7563.21], + ["hermite", 3, 2.22771, 61.711], + ["hermite", 2, -2.62859, 25.6379], + ["hermite", 6, -4.40261, 299560], + ["hermite", 9, 5.38028, 9.37244e8], + ["hermite", 9, -2.61379, 224091], + ["hermite", 9, -3.36389, -1.19209e6], + ["hermite", 10, -8.87142, 2.28415e12], + ["hermite", 4, 7.97235, 61596], + ["hermite", 9, 2.67941, -281217], + ["hermite", 9, 1.38544, -6245.48], + ["hermite", 0, 2.43679, 1], + ["hermite", 6, -2.25748, -446.214], + ["hermite", 0, 5.6625, 1], + ["hermite", 8, -0.514168, -998.753], + ["hermite", 2, 8.95195, 318.55], + ["hermite", 3, 5.49834, 1263.81], + ["hermite", 6, -9.35968, 3.94069e7], + ["hermite", 8, 8.37351, 5.01699e9], + ["hermite", 4, -1.58803, -7.29376], + ["hermite", 0, 8.33832, 1], + ["hermite", 9, 3.75904, 1.11329e7], + ["hermite", 9, -6.92943, -1.25365e10], + ["hermite", 4, 8.17652, 68317.5], + ["hermite", 8, -5.12804, 6.61876e7], + ["hermite", 0, -0.319694, 1], + ["hermite", 5, -3.19578, -5828.19], + ["hermite", 1, 1.20878, 2.41755], + ["hermite", 0, 2.9429, 1], + ["hermite", 4, 4.48321, 5510.87], + ["hermite", 5, -6.61207, -358965], + ["hermite", 0, -2.52742, 1], + ["hermite", 6, -9.95631, 5.7695e7], + ["assoc_laguerre", 8, 1, -5.56011, 15647.9], + ["assoc_laguerre", 10, 0, 4.42559, 2.02905], + ["assoc_laguerre", 6, 10, 3.41191, 609.264], + ["assoc_laguerre", 6, 9, -0.290177, 5935.75], + ["assoc_laguerre", 3, 8, 9.51122, -3.97165], + ["assoc_laguerre", 1, 5, -8.45613, 14.4561], + ["assoc_laguerre", 5, 0, -5.35991, 636.889], + ["assoc_laguerre", 8, 0, -0.547931, 11.409], + ["assoc_laguerre", 9, 0, -4.8598, 9919.3], + ["assoc_laguerre", 5, 6, -9.85883, 25624.1], + ["assoc_laguerre", 0, 0, 1.87133, 1], + ["assoc_laguerre", 6, 1, -6.85041, 5797.91], + ["assoc_laguerre", 9, 7, 0.379682, 7308.69], + ["assoc_laguerre", 8, 0, -0.881694, 27.3643], + ["assoc_laguerre", 3, 1, 1.77336, -1.28003], + ["assoc_laguerre", 8, 10, -7.53623, 2.04266e6], + ["assoc_laguerre", 3, 8, -6.98545, 874.391], + ["assoc_laguerre", 5, 8, -9.53106, 37472.9], + ["assoc_laguerre", 2, 1, -9.79528, 80.3596], + ["assoc_laguerre", 1, 1, -3.20664, 5.20664], + ["assoc_laguerre", 2, 5, -2.26807, 39.4486], + ["assoc_laguerre", 5, 8, -9.23033, 34783.8], + ["assoc_laguerre", 5, 4, 5.0366, 4.53018], + ["assoc_laguerre", 3, 0, -4.84053, 69.5705], + ["assoc_laguerre", 0, 9, -9.21993, 1], + ["assoc_laguerre", 9, 2, 3.11624, 1.23465], + ["assoc_laguerre", 5, 7, 1.1019, 366.128], + ["assoc_laguerre", 0, 3, -1.01414, 1], + ["assoc_laguerre", 3, 7, -8.58788, 980.776], + ["assoc_laguerre", 3, 3, -0.172142, 22.6719], + ["assoc_laguerre", 2, 6, -0.349016, 30.853], + ["assoc_laguerre", 4, 4, 1.58575, 11.3493], + ["assoc_laguerre", 0, 2, -8.61307, 1], + ["assoc_laguerre", 10, 10, -5.32705, 6.85926e6], + ["assoc_laguerre", 1, 2, 0.848012, 2.15199], + ["assoc_laguerre", 1, 8, 9.99805, -0.998052], + ["assoc_laguerre", 9, 8, -9.42609, 7.22511e6], + ["assoc_laguerre", 4, 1, -2.00423, 52.5084], + ["assoc_laguerre", 4, 3, 7.17027, 3.927], + ["assoc_laguerre", 0, 1, -2.52939, 1], + ["assoc_laguerre", 9, 4, 4.41667, 4.89364], + ["assoc_laguerre", 7, 5, -8.34293, 156792], + ["assoc_laguerre", 9, 4, -0.631878, 1952.13], + ["assoc_laguerre", 4, 0, -8.0054, 738.433], + ["assoc_laguerre", 8, 3, -4.21376, 18061.3], + ["assoc_laguerre", 10, 8, -3.46197, 849363], + ["assoc_laguerre", 9, 5, -4.20581, 122553], + ["assoc_laguerre", 9, 5, 3.06763, -11.4039], + ["assoc_laguerre", 4, 3, -3.55097, 350.546], + ["assoc_laguerre", 9, 1, 6.55966, 4.51354], + ["assoc_laguerre", 9, 3, -9.1953, 939101], + ["assoc_laguerre", 6, 10, 4.7066, 37.6665], + ["assoc_laguerre", 8, 1, -5.28604, 12774.5], + ["assoc_laguerre", 5, 3, 5.29, 4.93518], + ["assoc_laguerre", 7, 2, -8.42112, 53112.1], + ["assoc_laguerre", 10, 2, 6.87318, 6.10542], + ["assoc_laguerre", 10, 5, 5.23115, -11.5389], + ["assoc_laguerre", 7, 4, -9.44052, 172672], + ["assoc_laguerre", 2, 10, 4.3484, 23.2735], + ["assoc_laguerre", 3, 1, -3.55595, 58.1192], + ["assoc_laguerre", 8, 6, 4.83083, 25.0254], + ["assoc_laguerre", 9, 2, -4.19255, 20351.7], + ["assoc_laguerre", 5, 2, 3.25888, 1.49267], + ["assoc_laguerre", 4, 0, -1.15903, 10.7793], + ["assoc_laguerre", 1, 4, -4.94758, 9.94758], + ["assoc_laguerre", 8, 4, -5.98204, 95371.4], + ["assoc_laguerre", 5, 3, 7.39895, -5.12281], + ["assoc_laguerre", 4, 1, -5.30576, 356.302], + ["assoc_laguerre", 4, 0, -1.94497, 25.6299], + ["assoc_laguerre", 5, 1, 6.39062, -5.78954], + ["assoc_laguerre", 1, 9, -2.63015, 12.6302], + ["assoc_laguerre", 6, 8, -9.2628, 149449], + ["assoc_laguerre", 9, 3, -4.48693, 48225.9], + ["assoc_laguerre", 1, 10, -9.96379, 20.9638], + ["assoc_laguerre", 8, 5, -6.32624, 180710], + ["assoc_laguerre", 3, 10, -5.88608, 1004.3], + ["assoc_laguerre", 6, 0, -4.96478, 1174.94], + ["assoc_laguerre", 9, 4, -8.63735, 1.0762e6], + ["assoc_laguerre", 4, 9, 2.21793, 249.89], + ["assoc_laguerre", 9, 7, -7.85381, 2.49005e6], + ["assoc_laguerre", 7, 4, 9.05923, 2.0395], + ["assoc_laguerre", 10, 10, -0.462794, 277334], + ["assoc_laguerre", 5, 10, -5.34582, 20021.8], + ["assoc_laguerre", 9, 3, -7.44761, 357329], + ["assoc_laguerre", 0, 0, -3.63047, 1], + ["assoc_laguerre", 9, 5, -3.45376, 70401.9], + ["assoc_laguerre", 0, 4, 0.845471, 1], + ["assoc_laguerre", 4, 4, -8.29724, 2457.57], + ["assoc_laguerre", 9, 4, -6.23466, 278328], + ["assoc_laguerre", 0, 3, -1.97705, 1], + ["assoc_laguerre", 0, 1, 1.11498, 1], + ["assoc_laguerre", 1, 6, 1.24306, 5.75694], + ["assoc_laguerre", 8, 0, 4.62047, 1.03848], + ["assoc_laguerre", 3, 4, 5.58716, -2.14157], + ["assoc_laguerre", 7, 6, 1.26093, 364.593], + ["assoc_laguerre", 8, 10, -3.99046, 449423], + ["assoc_laguerre", 3, 3, 0.343607, 15.1933], + ["assoc_laguerre", 3, 6, 9.11024, 3.49586], + ["assoc_laguerre", 7, 7, 5.25613, -1.90456], + ["assoc_laguerre", 3, 3, -4.33736, 155.098], + ["assoc_legendre", 5, 6, 0.246109, 0], + ["assoc_legendre", 7, 9, 0.0959347, 0], + ["assoc_legendre", 9, 10, 0.799802, 0], + ["assoc_legendre", 9, 2, -0.364322, -7.6804], + ["assoc_legendre", 3, 6, -0.954549, 0], + ["assoc_legendre", 7, 1, 0.78675, 2.52538], + ["assoc_legendre", 5, 7, -0.455507, 0], + ["assoc_legendre", 9, 10, -0.618458, 0], + ["assoc_legendre", 0, 2, -0.249328, 0], + ["assoc_legendre", 9, 10, 0.414676, 0], + ["assoc_legendre", 2, 7, 0.0744382, 0], + ["assoc_legendre", 6, 9, 0.603221, 0], + ["assoc_legendre", 9, 10, -0.469774, 0], + ["assoc_legendre", 9, 8, -0.69662, -1.68497e6], + ["assoc_legendre", 5, 5, 0.453746, -531.055], + ["assoc_legendre", 5, 6, 0.610315, 0], + ["assoc_legendre", 2, 2, -0.685753, 1.58923], + ["assoc_legendre", 0, 4, 0.704456, 0], + ["assoc_legendre", 6, 5, -0.981828, 2.51222], + ["assoc_legendre", 2, 6, -0.545978, 0], + ["assoc_legendre", 2, 1, -0.118695, 0.353568], + ["assoc_legendre", 6, 0, 0.89993, -0.241552], + ["assoc_legendre", 7, 3, -0.82078, -172.023], + ["assoc_legendre", 2, 0, 0.18563, -0.448312], + ["assoc_legendre", 10, 4, 0.356737, 2707.55], + ["assoc_legendre", 7, 8, -0.971158, 0], + ["assoc_legendre", 5, 5, -0.656202, -231.193], + ["assoc_legendre", 5, 5, 0.0633444, -935.549], + ["assoc_legendre", 9, 2, -0.979377, -29.8628], + ["assoc_legendre", 2, 7, -0.605857, 0], + ["assoc_legendre", 2, 10, 0.328756, 0], + ["assoc_legendre", 7, 4, 0.230915, -827.072], + ["assoc_legendre", 2, 1, -0.305359, 0.872322], + ["assoc_legendre", 1, 3, -0.452583, 0], + ["assoc_legendre", 8, 9, -0.764506, 0], + ["assoc_legendre", 6, 3, -0.190821, -73.8969], + ["assoc_legendre", 4, 8, 0.885521, 0], + ["assoc_legendre", 0, 4, 0.933209, 0], + ["assoc_legendre", 0, 10, -0.415395, 0], + ["assoc_legendre", 2, 2, -0.656632, 1.7065], + ["assoc_legendre", 4, 5, 0.692216, 0], + ["assoc_legendre", 1, 2, -0.223691, 0], + ["assoc_legendre", 9, 8, 0.475711, 5.87408e6], + ["assoc_legendre", 4, 3, -0.868657, 11.0902], + ["assoc_legendre", 6, 0, -0.574362, 0.228182], + ["assoc_legendre", 6, 7, 0.372751, 0], + ["assoc_legendre", 6, 9, 0.919761, 0], + ["assoc_legendre", 6, 8, -0.275332, 0], + ["assoc_legendre", 2, 0, 0.75034, 0.344515], + ["assoc_legendre", 3, 6, -0.312883, 0], + ["assoc_legendre", 5, 1, 0.632117, 1.80332], + ["assoc_legendre", 3, 5, 0.00540365, 0], + ["assoc_legendre", 4, 3, 0.798751, -18.2666], + ["assoc_legendre", 0, 7, 0.100493, 0], + ["assoc_legendre", 10, 2, 0.513729, 21.9344], + ["assoc_legendre", 7, 3, -0.149192, -60.977], + ["assoc_legendre", 10, 3, 0.757559, 277.028], + ["assoc_legendre", 4, 0, 0.937364, 0.457677], + ["assoc_legendre", 3, 4, 0.639471, 0], + ["assoc_legendre", 7, 8, 0.397962, 0], + ["assoc_legendre", 9, 8, -0.970039, -405.702], + ["assoc_legendre", 8, 7, 0.181088, -326639], + ["assoc_legendre", 2, 10, 0.674011, 0], + ["assoc_legendre", 0, 4, -0.100379, 0], + ["assoc_legendre", 6, 10, 0.993968, 0], + ["assoc_legendre", 7, 10, -0.305816, 0], + ["assoc_legendre", 4, 8, -0.20189, 0], + ["assoc_legendre", 2, 8, -0.830613, 0], + ["assoc_legendre", 9, 0, -0.0967429, -0.206575], + ["assoc_legendre", 6, 0, 0.731047, -0.224596], + ["assoc_legendre", 0, 2, -0.3419, 0], + ["assoc_legendre", 8, 6, -0.0492673, -64634.5], + ["assoc_legendre", 7, 9, -0.0206372, 0], + ["assoc_legendre", 4, 4, -0.717119, 24.7741], + ["assoc_legendre", 3, 7, -0.355589, 0], + ["assoc_legendre", 0, 8, -0.89528, 0], + ["assoc_legendre", 9, 8, 0.277641, 6.94127e6], + ["assoc_legendre", 9, 1, -0.776337, 1.60341], + ["assoc_legendre", 2, 2, 0.0240907, 2.99826], + ["assoc_legendre", 2, 5, -0.474824, 0], + ["assoc_legendre", 0, 9, -0.039836, 0], + ["assoc_legendre", 0, 0, 0.784754, 1], + ["assoc_legendre", 6, 1, 0.614487, 2.06507], + ["assoc_legendre", 5, 4, 0.666625, 194.471], + ["assoc_legendre", 0, 4, -0.395557, 0], + ["assoc_legendre", 8, 10, 0.290334, 0], + ["assoc_legendre", 6, 8, 0.171052, 0], + ["assoc_legendre", 10, 10, 0.0301052, 6.51767e8], + ["assoc_legendre", 5, 9, 0.932685, 0], + ["assoc_legendre", 2, 0, 0.649127, 0.132049], + ["assoc_legendre", 10, 8, -0.458004, 2.00598e7], + ["assoc_legendre", 4, 3, -0.751059, 22.6965], + ["assoc_legendre", 4, 4, 0.216443, 95.3924], + ["assoc_legendre", 6, 2, -0.62567, -7.90168], + ["assoc_legendre", 0, 4, 0.299177, 0], + ["assoc_legendre", 8, 0, 0.165673, 0.0421266], + ["assoc_legendre", 1, 3, 0.749081, 0], + ["assoc_legendre", 10, 7, -0.438055, 770953], + ["assoc_legendre", 10, 10, 0.503198, 1.52076e8], + ["assoc_legendre", 6, 8, -0.400661, 0], + ["riemann_zeta", 1.18576, 5.97385], + ["riemann_zeta", 9.1875, 1.00176], + ["riemann_zeta", 5.58812, 1.02359], + ["riemann_zeta", 7.35446, 1.00647], + ["riemann_zeta", 1.25539, 4.51107], + ["riemann_zeta", 7.61548, 1.00536], + ["riemann_zeta", -2.78231, 0.00911049], + ["riemann_zeta", 2.97002, 1.20811], + ["riemann_zeta", 8.2331, 1.00345], + ["riemann_zeta", 5.58753, 1.0236], + ["riemann_zeta", -9.26353, -0.00776192], + ["riemann_zeta", -3.34015, 0.00586759], + ["riemann_zeta", 9.29878, 1.00163], + ["riemann_zeta", -2.78366, 0.00910845], + ["riemann_zeta", 4.27491, 1.06561], + ["riemann_zeta", -6.48105, 0.00265857], + ["riemann_zeta", 6.88098, 1.0091], + ["riemann_zeta", 2.56604, 1.31712], + ["riemann_zeta", -1.03913, -0.0770475], + ["riemann_zeta", -5.05815, -0.00391993], + ["riemann_zeta", -9.50369, -0.00664474], + ["riemann_zeta", 3.61958, 1.11401], + ["riemann_zeta", -8.6527, -0.00564677], + ["riemann_zeta", -6.41665, 0.00234529], + ["riemann_zeta", 5.28373, 1.0297], + ["riemann_zeta", 7.94791, 1.00423], + ["riemann_zeta", 8.44276, 1.00298], + ["riemann_zeta", 9.59082, 1.00133], + ["riemann_zeta", 6.85688, 1.00926], + ["riemann_zeta", 7.78719, 1.00475], + ["riemann_zeta", 0.840867, -5.71853], + ["riemann_zeta", -4.76773, -0.00385361], + ["riemann_zeta", -4.5256, -0.00319357], + ["riemann_zeta", 8.95004, 1.00208], + ["riemann_zeta", -2.59764, 0.008975], + ["riemann_zeta", -2.46923, 0.00830787], + ["riemann_zeta", 6.585, 1.01128], + ["riemann_zeta", 0.299112, -0.902819], + ["riemann_zeta", -5.67982, -0.0018085], + ["riemann_zeta", 5.39082, 1.02738], + ["riemann_zeta", -4.68787, -0.00369718], + ["riemann_zeta", -5.01897, -0.00395578], + ["riemann_zeta", -2.86789, 0.00890723], + ["riemann_zeta", 6.62512, 1.01096], + ["riemann_zeta", 0.563095, -1.74432], + ["riemann_zeta", -0.318079, -0.284759], + ["riemann_zeta", 2.49736, 1.34251], + ["riemann_zeta", -8.12124, -0.00104034], + ["riemann_zeta", -6.90041, 0.00404745], + ["riemann_zeta", -7.78105, 0.00167594], + ["riemann_zeta", -0.555241, -0.18883], + ["riemann_zeta", -9.52722, -0.0064623], + ["riemann_zeta", -1.50551, -0.0250665], + ["riemann_zeta", 3.83129, 1.09494], + ["riemann_zeta", -9.41783, -0.00719791], + ["riemann_zeta", 0.989137, -91.4817], + ["riemann_zeta", -0.414784, -0.240932], + ["riemann_zeta", 6.17256, 1.01527], + ["riemann_zeta", 2.0869, 1.57037], + ["riemann_zeta", 6.41624, 1.01276], + ["riemann_zeta", -5.5688, -0.00235996], + ["riemann_zeta", -1.13806, -0.0627227], + ["riemann_zeta", -2.42862, 0.00798053], + ["riemann_zeta", 6.07372, 1.01642], + ["riemann_zeta", -9.85926, -0.0024607], + ["riemann_zeta", 1.43837, 2.88937], + ["riemann_zeta", 8.71608, 1.00245], + ["riemann_zeta", -3.24376, 0.00666953], + ["riemann_zeta", -6.30527, 0.00176085], + ["riemann_zeta", -2.06886, 0.00194524], + ["riemann_zeta", 7.49139, 1.00586], + ["riemann_zeta", -2.12126, 0.00323249], + ["riemann_zeta", 1.07419, 14.0622], + ["riemann_zeta", -6.45054, 0.00251268], + ["riemann_zeta", -7.47991, 0.00335443], + ["riemann_zeta", 2.7766, 1.25308], + ["riemann_zeta", 7.83887, 1.00457], + ["riemann_zeta", 5.1833, 1.03207], + ["riemann_zeta", 3.04372, 1.19362], + ["riemann_zeta", -4.2629, -0.00187126], + ["riemann_zeta", -6.41217, 0.00232279], + ["riemann_zeta", -2.34414, 0.00709775], + ["riemann_zeta", -9.24886, -0.00778802], + ["riemann_zeta", 2.04437, 1.60521], + ["riemann_zeta", 8.45229, 1.00296], + ["riemann_zeta", -3.23682, 0.00672484], + ["riemann_zeta", 3.79976, 1.09753], + ["riemann_zeta", 5.6916, 1.02182], + ["riemann_zeta", -8.94566, -0.00738175], + ["riemann_zeta", -7.46082, 0.00343178], + ["riemann_zeta", 0.853436, -6.2565], + ["riemann_zeta", -1.48197, -0.0268811], + ["riemann_zeta", 3.91482, 1.08844], + ["riemann_zeta", -4.4857, -0.00303214], + ["riemann_zeta", 5.53541, 1.02454], + ["riemann_zeta", 4.83155, 1.0421], + ["riemann_zeta", -1.46733, -0.0280456], + ["riemann_zeta", 6.36686, 1.01323], + ["riemann_zeta", 7.68771, 1.00509], + ["riemann_zeta", -0.724008, -0.140067], + ["clamp", 1, 6, 5, 5], +]; diff --git a/src/test/numeric/test_numeric_algorithms.ts b/src/test/numeric/test_numeric_algorithms.ts index e32474f0..f27956df 100644 --- a/src/test/numeric/test_numeric_algorithms.ts +++ b/src/test/numeric/test_numeric_algorithms.ts @@ -1,119 +1,118 @@ import * as std from "../../index"; - import { Point2D } from "../internal/Point2D"; export function test_numeric_algorithms(): void { - //---- - // CONSTRUCT BASIC DATA - //---- - const x: std.Vector = new std.Vector(); - const y: std.Vector = new std.Vector(); - - for (let i: number = 0; i < 10; ++i) { - x.push_back(new Point2D(std.randint(0, 100), std.randint(0, 100))); - y.push_back(new Point2D(std.randint(0, 100), std.randint(0, 100))); - } - - //---- - // DO TEST - //---- - // COMMON ALGORITHMS - _Test_accumulate(x); - _Test_inner_product(x, y); - _Test_adjacent_difference(x); - _Test_partial_sum(x); - - // PREFIX SUMS - _Test_inclusive_scan(x); - _Test_exclusive_scan(x); + //---- + // CONSTRUCT BASIC DATA + //---- + const x: std.Vector = new std.Vector(); + const y: std.Vector = new std.Vector(); + + for (let i: number = 0; i < 10; ++i) { + x.push_back(new Point2D(std.randint(0, 100), std.randint(0, 100))); + y.push_back(new Point2D(std.randint(0, 100), std.randint(0, 100))); + } + + //---- + // DO TEST + //---- + // COMMON ALGORITHMS + _Test_accumulate(x); + _Test_inner_product(x, y); + _Test_adjacent_difference(x); + _Test_partial_sum(x); + + // PREFIX SUMS + _Test_inclusive_scan(x); + _Test_exclusive_scan(x); } /* --------------------------------------------------------- COMMON ALGORITHMS --------------------------------------------------------- */ function _Test_accumulate(vec: std.Vector): void { - let solution: Point2D = new Point2D(); - for (const elem of vec) solution = std.plus(solution, elem); + let solution: Point2D = new Point2D(); + for (const elem of vec) solution = std.plus(solution, elem); - const ret: Point2D = std.accumulate(vec.begin(), vec.end(), new Point2D()); - if (!std.equal_to(solution, ret)) - throw new std.DomainError("Bug on std.accumulate()."); + const ret: Point2D = std.accumulate(vec.begin(), vec.end(), new Point2D()); + if (!std.equal_to(solution, ret)) + throw new std.DomainError("Bug on std.accumulate()."); } function _Test_inner_product( - x: std.Vector, - y: std.Vector, + x: std.Vector, + y: std.Vector, ): void { - let solution: Point2D = new Point2D(); - for (let i: number = 0; i < x.size(); ++i) - solution = std.plus(solution, std.multiplies(x.at(i), y.at(i))); - - const ret: Point2D = std.inner_product( - x.begin(), - x.end(), - y.begin(), - new Point2D(), - ); - if (!std.equal_to(solution, ret)) - throw new std.DomainError("Bug on std.inner_product()."); + let solution: Point2D = new Point2D(); + for (let i: number = 0; i < x.size(); ++i) + solution = std.plus(solution, std.multiplies(x.at(i), y.at(i))); + + const ret: Point2D = std.inner_product( + x.begin(), + x.end(), + y.begin(), + new Point2D(), + ); + if (!std.equal_to(solution, ret)) + throw new std.DomainError("Bug on std.inner_product()."); } function _Test_adjacent_difference(vec: std.Vector): void { - const solution: std.Vector = new std.Vector([vec.front()]); - for (let i: number = 1; i < vec.size(); ++i) - solution.push_back(std.minus(vec.at(i), vec.at(i - 1))); + const solution: std.Vector = new std.Vector([vec.front()]); + for (let i: number = 1; i < vec.size(); ++i) + solution.push_back(std.minus(vec.at(i), vec.at(i - 1))); - const ret: std.Vector = new std.Vector(); - std.adjacent_difference(vec.begin(), vec.end(), std.back_inserter(ret)); + const ret: std.Vector = new std.Vector(); + std.adjacent_difference(vec.begin(), vec.end(), std.back_inserter(ret)); - if (std.equal(solution.begin(), solution.end(), ret.begin()) === false) - throw new std.DomainError("Bug on std.adjacent_difference()."); + if (std.equal(solution.begin(), solution.end(), ret.begin()) === false) + throw new std.DomainError("Bug on std.adjacent_difference()."); } function _Test_partial_sum(vec: std.Vector): void { - const solution: std.Vector = new std.Vector(); - let sum: Point2D = new Point2D(); + const solution: std.Vector = new std.Vector(); + let sum: Point2D = new Point2D(); - for (const elem of vec) { - sum = std.plus(sum, elem); - solution.push_back(sum); - } + for (const elem of vec) { + sum = std.plus(sum, elem); + solution.push_back(sum); + } - const ret: std.Vector = new std.Vector(); - std.partial_sum(vec.begin(), vec.end(), std.back_inserter(ret)); + const ret: std.Vector = new std.Vector(); + std.partial_sum(vec.begin(), vec.end(), std.back_inserter(ret)); - if (std.equal(solution.begin(), solution.end(), ret.begin()) === false) - throw new std.DomainError("Bug on std.partial_sum()."); + if (std.equal(solution.begin(), solution.end(), ret.begin()) === false) + throw new std.DomainError("Bug on std.partial_sum()."); } /* --------------------------------------------------------- PREFIX SUMS --------------------------------------------------------- */ function _Test_inclusive_scan(vec: std.Vector): void { - const solution: std.Vector = new std.Vector([vec.front()]); - for (let i: number = 1; i < vec.size(); ++i) - solution.push_back(std.plus(vec.at(i), solution.at(i - 1))); + const solution: std.Vector = new std.Vector([vec.front()]); + for (let i: number = 1; i < vec.size(); ++i) + solution.push_back(std.plus(vec.at(i), solution.at(i - 1))); - const ret: std.Vector = new std.Vector(); - std.inclusive_scan(vec.begin(), vec.end(), std.back_inserter(ret)); + const ret: std.Vector = new std.Vector(); + std.inclusive_scan(vec.begin(), vec.end(), std.back_inserter(ret)); - if (std.equal(solution.begin(), solution.end(), ret.begin()) === false) - throw new std.DomainError("Bug on std.transform_inclusive_scan()."); + if (std.equal(solution.begin(), solution.end(), ret.begin()) === false) + throw new std.DomainError("Bug on std.transform_inclusive_scan()."); } function _Test_exclusive_scan(vec: std.Vector): void { - const solution: std.Vector = new std.Vector([new Point2D()]); - for (let i: number = 0; i < vec.size() - 1; ++i) - solution.push(std.plus(vec.at(i), solution.at(i))); - - const ret: std.Vector = new std.Vector(); - std.exclusive_scan( - vec.begin(), - vec.end(), - std.back_inserter(ret), - new Point2D(), - ); - - if (std.equal(solution.begin(), solution.end(), ret.begin()) === false) - throw new std.DomainError("Bug on std.exclusive_scan()."); + const solution: std.Vector = new std.Vector([new Point2D()]); + for (let i: number = 0; i < vec.size() - 1; ++i) + solution.push(std.plus(vec.at(i), solution.at(i))); + + const ret: std.Vector = new std.Vector(); + std.exclusive_scan( + vec.begin(), + vec.end(), + std.back_inserter(ret), + new Point2D(), + ); + + if (std.equal(solution.begin(), solution.end(), ret.begin()) === false) + throw new std.DomainError("Bug on std.exclusive_scan()."); } diff --git a/src/test/numeric/test_special_maths.ts b/src/test/numeric/test_special_maths.ts index d5135968..c220298a 100644 --- a/src/test/numeric/test_special_maths.ts +++ b/src/test/numeric/test_special_maths.ts @@ -1,68 +1,66 @@ import * as fs from "fs"; + import * as std from "../../index"; const PATH = - __filename.substr(-2) === "ts" - ? `${__dirname}/special_math` - : `${__dirname}/special_math`.replace("lib", "src"); + __filename.substr(-2) === "ts" + ? `${__dirname}/special_math` + : `${__dirname}/special_math`.replace("lib", "src"); export function similar(x: number, y: number, precision = 0.05): boolean { - const diff: number = _Difference(x, y); + const diff: number = _Difference(x, y); - return diff < precision; + return diff < precision; } export function test_special_maths(): void { - const content: string = fs - .readFileSync(PATH + "/data.json") - .toString("utf8"); - const solutions: ISolution[] = JSON.parse(content); - - // TRACING ERRORS - const aggregates: std.HashMap = new std.HashMap(); - let output: string = ""; - - for (const solve of solutions) { - const name: string = solve[0]; - const func: Function = (std as any)[name]; - const args: number[] = solve.slice(1, solve.length - 1) as number[]; - - const ret: number = func(...args); - const answer: number = solve[solve.length - 1] as number; - let difference: number = _Difference(answer, ret); - - if (isNaN(difference)) difference = 1.0; - - if (!similar(ret, answer, 0.1)) { - let it = aggregates.find(name); - if (it.equals(aggregates.end()) === true) - it = aggregates.emplace(name, 0).first; - - ++it.second; - output += `std.${name}(${args.toString()}) = ${answer} && ${ret} -> ${difference}\n`; - } + const content: string = fs.readFileSync(PATH + "/data.json").toString("utf8"); + const solutions: ISolution[] = JSON.parse(content); + + // TRACING ERRORS + const aggregates: std.HashMap = new std.HashMap(); + let output: string = ""; + + for (const solve of solutions) { + const name: string = solve[0]; + const func: Function = (std as any)[name]; + const args: number[] = solve.slice(1, solve.length - 1) as number[]; + + const ret: number = func(...args); + const answer: number = solve[solve.length - 1] as number; + let difference: number = _Difference(answer, ret); + + if (isNaN(difference)) difference = 1.0; + + if (!similar(ret, answer, 0.1)) { + let it = aggregates.find(name); + if (it.equals(aggregates.end()) === true) + it = aggregates.emplace(name, 0).first; + + ++it.second; + output += `std.${name}(${args.toString()}) = ${answer} && ${ret} -> ${difference}\n`; } + } - if (aggregates.empty() === false) - fs.writeFileSync(PATH + "errors.log", output, "utf8"); + if (aggregates.empty() === false) + fs.writeFileSync(PATH + "errors.log", output, "utf8"); - let validate: boolean = true; - for (const entry of aggregates) if (entry.second > 5) validate = false; + let validate: boolean = true; + for (const entry of aggregates) if (entry.second > 5) validate = false; - if (!validate) - throw new std.DomainError("Bug on special math function(s)."); + if (!validate) throw new std.DomainError("Bug on special math function(s)."); } function _Difference(x: number, y: number): number { - if (x === 0 && y === 0) return 0; - else if (isNaN(x) && isNaN(y)) return 0; - else if (Math.abs(x - y) < Math.pow(10, -5)) return 0; + if (x === 0 && y === 0) return 0; + else if (isNaN(x) && isNaN(y)) return 0; + else if (Math.abs(x - y) < Math.pow(10, -5)) return 0; - const diff: number = Math.abs(y - x); - if ((x === 0 || y === 0) && diff < 0.00001) return 0; - else return diff / Math.max(Math.abs(x), Math.abs(y)); + const diff: number = Math.abs(y - x); + if ((x === 0 || y === 0) && diff < 0.00001) return 0; + else return diff / Math.max(Math.abs(x), Math.abs(y)); } interface ISolution extends Array { - 0: string; + 0: string; } diff --git a/src/test/test_exports.ts b/src/test/test_exports.ts index 9ae14bb6..25416342 100644 --- a/src/test/test_exports.ts +++ b/src/test/test_exports.ts @@ -1,7 +1,7 @@ import * as fs from "fs"; -import * as index from "../index"; import { HashMap } from "../container/HashMap"; +import * as index from "../index"; import { sort } from "../ranges/algorithm/sorting"; import { ArrayUtil } from "./internal/ArrayUtil"; @@ -10,76 +10,75 @@ const HELPERS = [MAIN + "/benchmark", MAIN + "/test"]; const EXCLUDES = ["internal"]; async function from_dynamic( - map: HashMap, - path: string, + map: HashMap, + path: string, ): Promise { - const fileList: string[] = await fs.promises.readdir(path); - for (const file of fileList) { - const current: string = `${path}/${file}`; - const stats: fs.Stats = await fs.promises.stat(current); + const fileList: string[] = await fs.promises.readdir(path); + for (const file of fileList) { + const current: string = `${path}/${file}`; + const stats: fs.Stats = await fs.promises.stat(current); + if ( + stats.isDirectory() && + ArrayUtil.has(HELPERS, current) === false && + ArrayUtil.has(EXCLUDES, file) === false + ) + await from_dynamic(map, current); + else if ( + file.substr(-3) === __filename.substr(-3) && + __filename.substr(-5) !== ".d.ts" + ) { + const elem: any = await import(current); + for (const key in elem) { + const instance: any = elem[key]; + if (!instance) continue; + + const type: string = typeof instance; if ( - stats.isDirectory() && - ArrayUtil.has(HELPERS, current) === false && - ArrayUtil.has(EXCLUDES, file) === false + type === "function" || + (type === "object" && + !( + instance.constructor === Object && key[0].toLowerCase() === key[0] + )) ) - await from_dynamic(map, current); - else if ( - file.substr(-3) === __filename.substr(-3) && - __filename.substr(-5) !== ".d.ts" - ) { - const elem: any = await import(current); - for (const key in elem) { - const instance: any = elem[key]; - if (!instance) continue; - - const type: string = typeof instance; - if ( - type === "function" || - (type === "object" && - !( - instance.constructor === Object && - key[0].toLowerCase() === key[0] - )) - ) - map.set(instance, key); - } - } + map.set(instance, key); + } } + } } function from_index(map: HashMap, elem: any): void { - if (map.has(elem) === true) return; + if (map.has(elem) === true) return; - for (const key in elem) { - const instance: any = elem[key]; - const type: string = typeof instance; + for (const key in elem) { + const instance: any = elem[key]; + const type: string = typeof instance; - if (type === "object" && instance.constructor === Object) - if (key[0].toUpperCase() === key[0]) map.set(instance, key); - else from_index(map, instance); - else if (typeof instance === "function" || typeof instance === "object") - map.set(instance, key); - } + if (type === "object" && instance.constructor === Object) + if (key[0].toUpperCase() === key[0]) map.set(instance, key); + else from_index(map, instance); + else if (typeof instance === "function" || typeof instance === "object") + map.set(instance, key); + } } export async function test_exports(): Promise { - const dynamicMap: HashMap = new HashMap(); - const indexMap: HashMap = new HashMap(); + const dynamicMap: HashMap = new HashMap(); + const indexMap: HashMap = new HashMap(); - await from_dynamic(dynamicMap, MAIN); - from_index(indexMap, index); + await from_dynamic(dynamicMap, MAIN); + from_index(indexMap, index); - const ommissions: string[] = []; - for (const tuple of dynamicMap) - if (indexMap.has(tuple.first) === false) ommissions.push(tuple.second); + const ommissions: string[] = []; + for (const tuple of dynamicMap) + if (indexMap.has(tuple.first) === false) ommissions.push(tuple.second); - if (ommissions.length !== 0) { - sort(ommissions); - throw new Error( - "Error on module indexing: ommited " + - ommissions.join(", ") + - " components.", - ); - } + if (ommissions.length !== 0) { + sort(ommissions); + throw new Error( + "Error on module indexing: ommited " + + ommissions.join(", ") + + " components.", + ); + } } diff --git a/src/test/thread/test_condition_variables.ts b/src/test/thread/test_condition_variables.ts index 227ca221..149db8a5 100644 --- a/src/test/thread/test_condition_variables.ts +++ b/src/test/thread/test_condition_variables.ts @@ -4,57 +4,57 @@ const SLEEP_TIME: number = 100; const WAIT_COUNT: number = 10; export async function test_condition_variables(): Promise { - const cv: std.ConditionVariable = new std.ConditionVariable(); - let wait_count: number = 0; - - //---- - // WAIT & NOTIFY - //---- - // THERE'RE 10 WAITERS; HOLDERS - for (let i: number = 0; i < WAIT_COUNT; ++i) { - cv.wait().then(() => { - --wait_count; - }); - ++wait_count; - } - - // NOTIFY ONE - cv.notify_one(); - await std.sleep_for(SLEEP_TIME); - - if (wait_count !== WAIT_COUNT - 1) - throw new Error("Bug on ConditionVariable.notify_one()."); - - // NOTIFY ALL - cv.notify_all(); - await std.sleep_for(SLEEP_TIME); - - if (wait_count !== 0) - throw new Error("Bug on ConditionVariable.notify_all()."); - - //---- - // WAIT FOR & NOTIFY - //---- - let success_count: number = 0; - - // THERE'RE 10 WAITERS, HOLDERS, WITH DIFFERENT TIMES - for (let i: number = 0; i < WAIT_COUNT; ++i) { - cv.wait_for(i * SLEEP_TIME).then((ret) => { - if (ret === true) ++success_count; - }); - } - - // NOTIFY ONE - await cv.notify_one(); - - // NOTIFY ALL WHEN BE HALT TIME - await std.sleep_for((WAIT_COUNT * SLEEP_TIME) / 2.0); - cv.notify_all(); - - // VALIDATE SUCCESS COUNT - await std.sleep_for(SLEEP_TIME); - if (success_count < 3 || success_count > 7) - throw new Error( - "Bug on ConditionVariable.wait_for(): it does not work in exact time.", - ); + const cv: std.ConditionVariable = new std.ConditionVariable(); + let wait_count: number = 0; + + //---- + // WAIT & NOTIFY + //---- + // THERE'RE 10 WAITERS; HOLDERS + for (let i: number = 0; i < WAIT_COUNT; ++i) { + cv.wait().then(() => { + --wait_count; + }); + ++wait_count; + } + + // NOTIFY ONE + cv.notify_one(); + await std.sleep_for(SLEEP_TIME); + + if (wait_count !== WAIT_COUNT - 1) + throw new Error("Bug on ConditionVariable.notify_one()."); + + // NOTIFY ALL + cv.notify_all(); + await std.sleep_for(SLEEP_TIME); + + if (wait_count !== 0) + throw new Error("Bug on ConditionVariable.notify_all()."); + + //---- + // WAIT FOR & NOTIFY + //---- + let success_count: number = 0; + + // THERE'RE 10 WAITERS, HOLDERS, WITH DIFFERENT TIMES + for (let i: number = 0; i < WAIT_COUNT; ++i) { + cv.wait_for(i * SLEEP_TIME).then((ret) => { + if (ret === true) ++success_count; + }); + } + + // NOTIFY ONE + await cv.notify_one(); + + // NOTIFY ALL WHEN BE HALT TIME + await std.sleep_for((WAIT_COUNT * SLEEP_TIME) / 2.0); + cv.notify_all(); + + // VALIDATE SUCCESS COUNT + await std.sleep_for(SLEEP_TIME); + if (success_count < 3 || success_count > 7) + throw new Error( + "Bug on ConditionVariable.wait_for(): it does not work in exact time.", + ); } diff --git a/src/test/thread/test_mutable_singleton.ts b/src/test/thread/test_mutable_singleton.ts index 101c1085..b7de4292 100644 --- a/src/test/thread/test_mutable_singleton.ts +++ b/src/test/thread/test_mutable_singleton.ts @@ -1,34 +1,34 @@ import * as std from "../../index"; export async function test_mutable_singleton(): Promise { - // initlaize Singleton generator - let index: number = 0; - const singleton: std.MutableSingleton = new std.MutableSingleton( - async () => { - await std.sleep_for(std.randint(50, 250)); - return ++index; - }, - ); + // initlaize Singleton generator + let index: number = 0; + const singleton: std.MutableSingleton = new std.MutableSingleton( + async () => { + await std.sleep_for(std.randint(50, 250)); + return ++index; + }, + ); - // validate Singleton.get() - let promises: Promise[] = []; - for (let i: number = 0; i < 100; ++i) promises.push(singleton.get()); + // validate Singleton.get() + let promises: Promise[] = []; + for (let i: number = 0; i < 100; ++i) promises.push(singleton.get()); - let results: number[] = await Promise.all(promises); - if (results.some((value) => value !== 1)) - throw new Error( - "Error on Singleton.get(): the lazy-construction must be done in only one time.", - ); + let results: number[] = await Promise.all(promises); + if (results.some((value) => value !== 1)) + throw new Error( + "Error on Singleton.get(): the lazy-construction must be done in only one time.", + ); - // validate Singleton.reload() - promises = [singleton.reload()]; - for (let i: number = 0; i < 100; ++i) promises.push(singleton.get()); + // validate Singleton.reload() + promises = [singleton.reload()]; + for (let i: number = 0; i < 100; ++i) promises.push(singleton.get()); - results = await Promise.all(promises); - if (results.some((value) => value !== 2)) - throw new Error( - `Error on Singleton.reload(): must be 2 but ${results.find( - (value) => value !== 2, - )!}.`, - ); + results = await Promise.all(promises); + if (results.some((value) => value !== 2)) + throw new Error( + `Error on Singleton.reload(): must be 2 but ${results.find( + (value) => value !== 2, + )!}.`, + ); } diff --git a/src/test/thread/test_mutexes.ts b/src/test/thread/test_mutexes.ts index d7d2a187..055923ac 100644 --- a/src/test/thread/test_mutexes.ts +++ b/src/test/thread/test_mutexes.ts @@ -1,244 +1,243 @@ -import * as std from "../../index"; - -import { ITimedLockable } from "../../base/thread/ITimedLockable"; import { ISharedLockable } from "../../base/thread/ISharedLockable"; import { ISharedTimedLockable } from "../../base/thread/ISharedTimedLockable"; +import { ITimedLockable } from "../../base/thread/ITimedLockable"; +import * as std from "../../index"; const SLEEP_TIME: number = 50; const READ_COUNT: number = 10; export async function test_mutexes(): Promise { - await _Test_lock(new std.Mutex()); - await _Test_try_lock(new std.TimedMutex()); - await _Test_lock_shared(new std.SharedMutex()); - await _Test_try_lock_shared(new std.SharedTimedMutex()); + await _Test_lock(new std.Mutex()); + await _Test_try_lock(new std.TimedMutex()); + await _Test_lock_shared(new std.SharedMutex()); + await _Test_try_lock_shared(new std.SharedTimedMutex()); } /* --------------------------------------------------------- WRITE LOCK --------------------------------------------------------- */ export async function _Test_lock( - mtx: std.base.ILockable, - name: string = mtx.constructor.name, + mtx: std.base.ILockable, + name: string = mtx.constructor.name, ): Promise { - const start_time: number = Date.now(); - - // LOCK FOR A SECOND - mtx.lock(); - std.sleep_for(SLEEP_TIME).then(() => { - mtx.unlock(); - }); - - // TRY LOCK AGAIN - await mtx.lock(); - const elapsed_time: number = Date.now() - start_time; - await mtx.unlock(); - - if (elapsed_time < SLEEP_TIME * 0.95) - throw new Error( - `Bug on ${name}.lock() & unlock(): it does not work in exact time.`, - ); + const start_time: number = Date.now(); + + // LOCK FOR A SECOND + mtx.lock(); + std.sleep_for(SLEEP_TIME).then(() => { + mtx.unlock(); + }); + + // TRY LOCK AGAIN + await mtx.lock(); + const elapsed_time: number = Date.now() - start_time; + await mtx.unlock(); + + if (elapsed_time < SLEEP_TIME * 0.95) + throw new Error( + `Bug on ${name}.lock() & unlock(): it does not work in exact time.`, + ); } export async function _Test_try_lock( - mtx: ITimedLockable, - name: string = mtx.constructor.name, + mtx: ITimedLockable, + name: string = mtx.constructor.name, ): Promise { - await _Test_lock(mtx, name); - const start_time: number = Date.now(); - - // DO LOCK - let ret: boolean = await mtx.try_lock_for(SLEEP_TIME); - if (ret === false) - throw new Error( - `Bug on ${name}.try_lock_for(): it does not return exact value`, - ); - - // TRY LOCK AGAIN - ret = await mtx.try_lock_for(SLEEP_TIME); - const elapsed_time: number = Date.now() - start_time; - - if (ret === true) - throw new Error( - `Bug on ${name}.try_lock_for(): it does not return exact value`, - ); - else if (elapsed_time < SLEEP_TIME * 0.95) - throw new Error( - `Bug on ${name}.try_lock_for(): it does not work in exact time`, - ); - - await mtx.unlock(); + await _Test_lock(mtx, name); + const start_time: number = Date.now(); + + // DO LOCK + let ret: boolean = await mtx.try_lock_for(SLEEP_TIME); + if (ret === false) + throw new Error( + `Bug on ${name}.try_lock_for(): it does not return exact value`, + ); + + // TRY LOCK AGAIN + ret = await mtx.try_lock_for(SLEEP_TIME); + const elapsed_time: number = Date.now() - start_time; + + if (ret === true) + throw new Error( + `Bug on ${name}.try_lock_for(): it does not return exact value`, + ); + else if (elapsed_time < SLEEP_TIME * 0.95) + throw new Error( + `Bug on ${name}.try_lock_for(): it does not work in exact time`, + ); + + await mtx.unlock(); } /* --------------------------------------------------------- READ LOCK --------------------------------------------------------- */ async function _Test_lock_shared( - mtx: std.base.ILockable & ISharedLockable, + mtx: std.base.ILockable & ISharedLockable, ): Promise { - // TEST WRITING LOCK & UNLOCK - await _Test_lock(mtx); - - //---- - // READ SIMULTANEOUSLY - //---- - // READ LOCK; 10 TIMES - let read_count: number = 0; - for (let i: number = 0; i < READ_COUNT; ++i) { - mtx.lock_shared(); - ++read_count; - } - if (read_count !== READ_COUNT) - // READ LOCK CAN BE DONE SIMULTANEOUSLY - throw new Error( - `Bug on ${mtx.constructor.name}.lock_shared(): it doesn't support the simultaneous lock.`, - ); - - //---- - // READ FIRST, WRITE LATER - //---- - let start_time: number = Date.now(); - std.sleep_for(SLEEP_TIME).then(() => { - // SLEEP FOR A SECOND AND UNLOCK ALL READINGS - for (let i: number = 0; i < READ_COUNT; ++i) mtx.unlock_shared(); - }); - - // DO WRITE LOCK; MUST BE BLOCKED - await mtx.lock(); - - // VALIDATE ELAPSED TIME - let elapsed_time: number = Date.now() - start_time; - if (elapsed_time < SLEEP_TIME * 0.95) - throw new Error( - `Bug on ${mtx.constructor.name}.lock(): it does not block writing while reading.`, - ); - - //---- - // WRITE FIRST, READ LATER - //---- - start_time = Date.now(); - std.sleep_for(SLEEP_TIME).then(() => { - // SLEEP FOR A SECOND AND UNLOCK WRITINGS - mtx.unlock(); - }); - for (let i: number = 0; i < READ_COUNT; ++i) await mtx.lock_shared(); - - // VALIDATE ELAPSED TIME - elapsed_time = Date.now() - start_time; - if (elapsed_time < SLEEP_TIME * 0.95) - throw new Error( - `Bug on ${mtx.constructor.name}.lock_shared(): it does not block reading while writing.`, - ); - - // RELEASE READING LOCK FOR THE NEXT STEP - for (let i: number = 0; i < READ_COUNT; ++i) await mtx.unlock_shared(); + // TEST WRITING LOCK & UNLOCK + await _Test_lock(mtx); + + //---- + // READ SIMULTANEOUSLY + //---- + // READ LOCK; 10 TIMES + let read_count: number = 0; + for (let i: number = 0; i < READ_COUNT; ++i) { + mtx.lock_shared(); + ++read_count; + } + if (read_count !== READ_COUNT) + // READ LOCK CAN BE DONE SIMULTANEOUSLY + throw new Error( + `Bug on ${mtx.constructor.name}.lock_shared(): it doesn't support the simultaneous lock.`, + ); + + //---- + // READ FIRST, WRITE LATER + //---- + let start_time: number = Date.now(); + std.sleep_for(SLEEP_TIME).then(() => { + // SLEEP FOR A SECOND AND UNLOCK ALL READINGS + for (let i: number = 0; i < READ_COUNT; ++i) mtx.unlock_shared(); + }); + + // DO WRITE LOCK; MUST BE BLOCKED + await mtx.lock(); + + // VALIDATE ELAPSED TIME + let elapsed_time: number = Date.now() - start_time; + if (elapsed_time < SLEEP_TIME * 0.95) + throw new Error( + `Bug on ${mtx.constructor.name}.lock(): it does not block writing while reading.`, + ); + + //---- + // WRITE FIRST, READ LATER + //---- + start_time = Date.now(); + std.sleep_for(SLEEP_TIME).then(() => { + // SLEEP FOR A SECOND AND UNLOCK WRITINGS + mtx.unlock(); + }); + for (let i: number = 0; i < READ_COUNT; ++i) await mtx.lock_shared(); + + // VALIDATE ELAPSED TIME + elapsed_time = Date.now() - start_time; + if (elapsed_time < SLEEP_TIME * 0.95) + throw new Error( + `Bug on ${mtx.constructor.name}.lock_shared(): it does not block reading while writing.`, + ); + + // RELEASE READING LOCK FOR THE NEXT STEP + for (let i: number = 0; i < READ_COUNT; ++i) await mtx.unlock_shared(); } async function _Test_try_lock_shared( - mtx: ITimedLockable & ISharedTimedLockable, + mtx: ITimedLockable & ISharedTimedLockable, ): Promise { - // TEST WRITING LOCK & UNLOCK - await _Test_try_lock(mtx); - await _Test_lock_shared(mtx); - - let start_time: number; - let elapsed_time: number; - let flag: boolean; - - //---- - // READ SIMULTANEOUSLY - //---- - start_time = Date.now(); - - // READ LOCK; 10 TIMES - for (let i: number = 0; i < READ_COUNT; ++i) { - flag = await mtx.try_lock_shared_for(SLEEP_TIME); - if (flag === false) - throw new Error( - `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not return exact value.`, - ); - } - - // VALIDATE ELAPSED TIME - elapsed_time = Date.now() - start_time; - if (elapsed_time >= SLEEP_TIME) - throw new Error( - `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not support simultaneous lock.`, - ); - - //---- - // WRITE LOCK - //---- - // TRY WRITE LOCK ON READING - start_time = Date.now(); - flag = await mtx.try_lock_for(SLEEP_TIME); - elapsed_time = Date.now() - start_time; - + // TEST WRITING LOCK & UNLOCK + await _Test_try_lock(mtx); + await _Test_lock_shared(mtx); + + let start_time: number; + let elapsed_time: number; + let flag: boolean; + + //---- + // READ SIMULTANEOUSLY + //---- + start_time = Date.now(); + + // READ LOCK; 10 TIMES + for (let i: number = 0; i < READ_COUNT; ++i) { + flag = await mtx.try_lock_shared_for(SLEEP_TIME); + if (flag === false) + throw new Error( + `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not return exact value.`, + ); + } + + // VALIDATE ELAPSED TIME + elapsed_time = Date.now() - start_time; + if (elapsed_time >= SLEEP_TIME) + throw new Error( + `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not support simultaneous lock.`, + ); + + //---- + // WRITE LOCK + //---- + // TRY WRITE LOCK ON READING + start_time = Date.now(); + flag = await mtx.try_lock_for(SLEEP_TIME); + elapsed_time = Date.now() - start_time; + + if (flag === true) + throw new Error( + `Bug on ${mtx.constructor.name}.try_lock_for(): it does not return exact value while reading.`, + ); + else if (elapsed_time < SLEEP_TIME * 0.95) + throw new Error( + `Bug on ${mtx.constructor.name}.try_lock_for(): it does not block while reading.`, + ); + + // TRY WRITE LOCK AFTER READING + std.sleep_for(SLEEP_TIME).then(() => { + for (let i: number = 0; i < READ_COUNT; ++i) mtx.unlock_shared(); + }); + start_time = Date.now(); + flag = await mtx.try_lock_for(SLEEP_TIME); + elapsed_time = Date.now() - start_time; + + if (flag === false) + throw new Error( + `Bug on ${mtx.constructor.name}.try_lock_for(): it does not return exact value while reading.`, + ); + else if (elapsed_time < SLEEP_TIME * 0.95) + throw new Error( + `Bug on ${mtx.constructor.name}.try_lock_for(): it does not work in exact time.`, + ); + + //---- + // READ LOCK + //---- + // READ LOCK ON WRITING + start_time = Date.now(); + for (let i: number = 0; i < READ_COUNT; ++i) { + flag = await mtx.try_lock_shared_for(SLEEP_TIME); if (flag === true) - throw new Error( - `Bug on ${mtx.constructor.name}.try_lock_for(): it does not return exact value while reading.`, - ); - else if (elapsed_time < SLEEP_TIME * 0.95) - throw new Error( - `Bug on ${mtx.constructor.name}.try_lock_for(): it does not block while reading.`, - ); - - // TRY WRITE LOCK AFTER READING - std.sleep_for(SLEEP_TIME).then(() => { - for (let i: number = 0; i < READ_COUNT; ++i) mtx.unlock_shared(); - }); - start_time = Date.now(); - flag = await mtx.try_lock_for(SLEEP_TIME); - elapsed_time = Date.now() - start_time; - + throw new Error( + `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not return exact value while writing.`, + ); + } + elapsed_time = Date.now() - start_time; + + if (elapsed_time < SLEEP_TIME * READ_COUNT * 0.95) + throw new Error( + `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not work in exact time.`, + ); + + // READ LOCK AFTER WRITING + start_time = Date.now(); + std.sleep_for(SLEEP_TIME).then(() => { + mtx.unlock(); + }); + + for (let i: number = 0; i < READ_COUNT; ++i) { + flag = await mtx.try_lock_shared_for(SLEEP_TIME); if (flag === false) - throw new Error( - `Bug on ${mtx.constructor.name}.try_lock_for(): it does not return exact value while reading.`, - ); - else if (elapsed_time < SLEEP_TIME * 0.95) - throw new Error( - `Bug on ${mtx.constructor.name}.try_lock_for(): it does not work in exact time.`, - ); - - //---- - // READ LOCK - //---- - // READ LOCK ON WRITING - start_time = Date.now(); - for (let i: number = 0; i < READ_COUNT; ++i) { - flag = await mtx.try_lock_shared_for(SLEEP_TIME); - if (flag === true) - throw new Error( - `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not return exact value while writing.`, - ); - } - elapsed_time = Date.now() - start_time; - - if (elapsed_time < SLEEP_TIME * READ_COUNT * 0.95) - throw new Error( - `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not work in exact time.`, - ); - - // READ LOCK AFTER WRITING - start_time = Date.now(); - std.sleep_for(SLEEP_TIME).then(() => { - mtx.unlock(); - }); - - for (let i: number = 0; i < READ_COUNT; ++i) { - flag = await mtx.try_lock_shared_for(SLEEP_TIME); - if (flag === false) - throw new Error( - `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not return exact value after writing.`, - ); - } - elapsed_time = Date.now() - start_time; - - if (elapsed_time < SLEEP_TIME * 0.95 || elapsed_time >= SLEEP_TIME * 5.0) - throw new Error( - `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not work in exact time.`, - ); - - // RELEASE READING LOCK FOR THE NEXT STEP - for (let i: number = 0; i < READ_COUNT; ++i) await mtx.unlock_shared(); + throw new Error( + `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not return exact value after writing.`, + ); + } + elapsed_time = Date.now() - start_time; + + if (elapsed_time < SLEEP_TIME * 0.95 || elapsed_time >= SLEEP_TIME * 5.0) + throw new Error( + `Bug on ${mtx.constructor.name}.try_lock_shared_for(): it does not work in exact time.`, + ); + + // RELEASE READING LOCK FOR THE NEXT STEP + for (let i: number = 0; i < READ_COUNT; ++i) await mtx.unlock_shared(); } diff --git a/src/test/thread/test_safe_locks.ts b/src/test/thread/test_safe_locks.ts index deae94c8..7b8b6b8c 100644 --- a/src/test/thread/test_safe_locks.ts +++ b/src/test/thread/test_safe_locks.ts @@ -1,93 +1,93 @@ import * as std from "../../index"; export async function test_unique_locks(): Promise { - //---- - // PREPARE ASSETS - //---- - // BASIC MUTEX - const mtx: std.TimedMutex = new std.TimedMutex(); + //---- + // PREPARE ASSETS + //---- + // BASIC MUTEX + const mtx: std.TimedMutex = new std.TimedMutex(); - // PROCEDURES - const lambda = _Lambda.bind(undefined, true); - const trier = () => mtx.try_lock(); - const unlocker = () => mtx.unlock(); + // PROCEDURES + const lambda = _Lambda.bind(undefined, true); + const trier = () => mtx.try_lock(); + const unlocker = () => mtx.unlock(); - //---- - // DO TEST - //---- - // STATIC METHOHD - await _Test_lock( - "UniqueLock.lock()", - () => std.UniqueLock.lock(mtx, lambda), - trier, - unlocker, - ); - await _Test_lock( - "UniqueLock.try_lock()", - () => std.UniqueLock.try_lock(mtx, lambda), - trier, - unlocker, - ); - await _Test_lock( - "UniqueLock.try_lock_for()", - () => std.UniqueLock.try_lock_for(mtx, 50, lambda), - trier, - unlocker, - ); + //---- + // DO TEST + //---- + // STATIC METHOHD + await _Test_lock( + "UniqueLock.lock()", + () => std.UniqueLock.lock(mtx, lambda), + trier, + unlocker, + ); + await _Test_lock( + "UniqueLock.try_lock()", + () => std.UniqueLock.try_lock(mtx, lambda), + trier, + unlocker, + ); + await _Test_lock( + "UniqueLock.try_lock_for()", + () => std.UniqueLock.try_lock_for(mtx, 50, lambda), + trier, + unlocker, + ); } export async function test_shared_locks(): Promise { - //---- - // PREPARE ASSETS - //---- - // BASIC MUTEX - const mtx: std.SharedTimedMutex = new std.SharedTimedMutex(); + //---- + // PREPARE ASSETS + //---- + // BASIC MUTEX + const mtx: std.SharedTimedMutex = new std.SharedTimedMutex(); - // PROCEDURES - const lambda = _Lambda.bind(undefined, true); - const trier = () => mtx.try_lock(); - const unlocker = () => mtx.unlock(); + // PROCEDURES + const lambda = _Lambda.bind(undefined, true); + const trier = () => mtx.try_lock(); + const unlocker = () => mtx.unlock(); - //---- - // DO TEST - //---- - // STATIC METHOHD - await _Test_lock( - "SharedLock.lock()", - () => std.SharedLock.lock(mtx, lambda), - trier, - unlocker, - ); - await _Test_lock( - "SharedLock.try_lock()", - () => std.SharedLock.try_lock(mtx, lambda), - trier, - unlocker, - ); - await _Test_lock( - "SharedLock.try_lock_for()", - () => std.SharedLock.try_lock_for(mtx, 50, lambda), - trier, - unlocker, - ); + //---- + // DO TEST + //---- + // STATIC METHOHD + await _Test_lock( + "SharedLock.lock()", + () => std.SharedLock.lock(mtx, lambda), + trier, + unlocker, + ); + await _Test_lock( + "SharedLock.try_lock()", + () => std.SharedLock.try_lock(mtx, lambda), + trier, + unlocker, + ); + await _Test_lock( + "SharedLock.try_lock_for()", + () => std.SharedLock.try_lock_for(mtx, 50, lambda), + trier, + unlocker, + ); } async function _Test_lock( - name: string, - locker: () => Promise, - trier: () => Promise, - unlocker: () => Promise, + name: string, + locker: () => Promise, + trier: () => Promise, + unlocker: () => Promise, ): Promise { - try { - await locker(); - } catch {} + try { + await locker(); + } catch {} - if ((await trier()) === false) - throw new Error(`Bug on ${name}: invalid implementation.`); + if ((await trier()) === false) + throw new Error(`Bug on ${name}: invalid implementation.`); - await unlocker(); + await unlocker(); } function _Lambda(success: boolean): void { - if (!success) throw new Error("Throw error."); + if (!success) throw new Error("Throw error."); } diff --git a/src/test/thread/test_semaphores.ts b/src/test/thread/test_semaphores.ts index 3ea642fa..c0e42626 100644 --- a/src/test/thread/test_semaphores.ts +++ b/src/test/thread/test_semaphores.ts @@ -1,98 +1,97 @@ -import * as std from "../../index"; - import { ITimedLockable } from "../../base/thread/ITimedLockable"; +import * as std from "../../index"; import { _Test_lock, _Test_try_lock } from "./test_mutexes"; const SIZE = 8; export async function test_semaphores(): Promise { - //---- - // TEST MUTEX FEATURES - //---- - const mtx = new std.Semaphore(1); - const wrapper: ITimedLockable = std.Semaphore.get_lockable(mtx); - - await _Test_lock(wrapper, "Semaphore.Lockable"); - await _Test_try_lock(wrapper, "Semaphore.Lockable"); - - //---- - // TEST SPECIAL FEATURES OF SEMAPHORE - //---- - const semaphore = new std.Semaphore(SIZE); - - await _Test_semaphore(semaphore); - await _Test_timed_semaphore(semaphore); + //---- + // TEST MUTEX FEATURES + //---- + const mtx = new std.Semaphore(1); + const wrapper: ITimedLockable = std.Semaphore.get_lockable(mtx); + + await _Test_lock(wrapper, "Semaphore.Lockable"); + await _Test_try_lock(wrapper, "Semaphore.Lockable"); + + //---- + // TEST SPECIAL FEATURES OF SEMAPHORE + //---- + const semaphore = new std.Semaphore(SIZE); + + await _Test_semaphore(semaphore); + await _Test_timed_semaphore(semaphore); } async function _Test_semaphore(s: std.Semaphore): Promise { - let acquired_count: number = 0; - - // LOCK 4 TIMES - for (let i: number = 0; i < s.max(); ++i) { - await s.acquire(); - ++acquired_count; - } - if (acquired_count !== s.max()) throw new Error(`Bug on Semaphore.lock()`); - else if ((await s.try_acquire()) === true) - throw new Error(`Bug on Semaphore.try_lock()`); - - // LOCK 4 TIMES AGAIN -> THEY SHOULD BE HOLD - for (let i: number = 0; i < s.max(); ++i) - s.acquire().then(() => { - ++acquired_count; - }); - if (acquired_count !== s.max()) - throw new Error(`Bug on Semaphore.lock() when Semaphore is full`); - - // DO UNLOCK - await s.release(s.max()); - - if (acquired_count !== 2 * s.max()) - throw new Error(`Bug on Semaphore.unlock()`); - - // RELEASE UNRESOLVED LOCKS - await std.sleep_for(0); - await s.release(s.max()); + let acquired_count: number = 0; + + // LOCK 4 TIMES + for (let i: number = 0; i < s.max(); ++i) { + await s.acquire(); + ++acquired_count; + } + if (acquired_count !== s.max()) throw new Error(`Bug on Semaphore.lock()`); + else if ((await s.try_acquire()) === true) + throw new Error(`Bug on Semaphore.try_lock()`); + + // LOCK 4 TIMES AGAIN -> THEY SHOULD BE HOLD + for (let i: number = 0; i < s.max(); ++i) + s.acquire().then(() => { + ++acquired_count; + }); + if (acquired_count !== s.max()) + throw new Error(`Bug on Semaphore.lock() when Semaphore is full`); + + // DO UNLOCK + await s.release(s.max()); + + if (acquired_count !== 2 * s.max()) + throw new Error(`Bug on Semaphore.unlock()`); + + // RELEASE UNRESOLVED LOCKS + await std.sleep_for(0); + await s.release(s.max()); } async function _Test_timed_semaphore(ts: std.Semaphore): Promise { - // TRY LOCK FIRST - for (let i: number = 0; i < ts.max(); ++i) { - const flag: boolean = await ts.try_acquire_for(0); - if (flag === false) - throw new Error( - "Bug on TimedSemaphore.try_lock_for(); failed to lock when clear", - ); - } - - // TRY LOCK FOR -> MUST BE FAILED - if ((await ts.try_acquire_for(50)) === true) - throw new Error( - "Bug on TimedSemaphore.try_lock_for(); succeeded to lock when must be failed.", - ); - - // LOCK WOULD BE HOLD - let cnt: number = 0; - for (let i: number = 0; i < ts.max() / 2; ++i) - ts.acquire().then(() => { - ++cnt; - }); - - await std.sleep_for(100); - if (cnt === ts.max() / 2) - throw new Error( - "Bug on TimedSemaphore.try_lock_for(); failed to release holdings.", - ); - - // RELEASE AND LOCK - await ts.release(ts.max()); - - for (let i: number = 0; i < ts.max() / 2; ++i) { - const flag: boolean = await ts.try_acquire_for(100); - if (flag === false) - throw new Error( - "Bug on TimedSemaphore.try_lock_for(); failed to lock when released.", - ); - } - await ts.release(ts.max()); + // TRY LOCK FIRST + for (let i: number = 0; i < ts.max(); ++i) { + const flag: boolean = await ts.try_acquire_for(0); + if (flag === false) + throw new Error( + "Bug on TimedSemaphore.try_lock_for(); failed to lock when clear", + ); + } + + // TRY LOCK FOR -> MUST BE FAILED + if ((await ts.try_acquire_for(50)) === true) + throw new Error( + "Bug on TimedSemaphore.try_lock_for(); succeeded to lock when must be failed.", + ); + + // LOCK WOULD BE HOLD + let cnt: number = 0; + for (let i: number = 0; i < ts.max() / 2; ++i) + ts.acquire().then(() => { + ++cnt; + }); + + await std.sleep_for(100); + if (cnt === ts.max() / 2) + throw new Error( + "Bug on TimedSemaphore.try_lock_for(); failed to release holdings.", + ); + + // RELEASE AND LOCK + await ts.release(ts.max()); + + for (let i: number = 0; i < ts.max() / 2; ++i) { + const flag: boolean = await ts.try_acquire_for(100); + if (flag === false) + throw new Error( + "Bug on TimedSemaphore.try_lock_for(); failed to lock when released.", + ); + } + await ts.release(ts.max()); } diff --git a/src/test/thread/test_shared_mutexes.ts b/src/test/thread/test_shared_mutexes.ts index 7f3d741e..52aa28c5 100644 --- a/src/test/thread/test_shared_mutexes.ts +++ b/src/test/thread/test_shared_mutexes.ts @@ -1,85 +1,84 @@ import * as std from "../../index"; const enum Status { - START_READING = "Start Reading", - END_READING = "End Reading", - START_WRITING = "Start Writing", - END_WRITING = "End Writing", + START_READING = "Start Reading", + END_READING = "End Reading", + START_WRITING = "Start Writing", + END_WRITING = "End Writing", } const MAGNIFIER: number = 3; async function write( - mutex: std.SharedTimedMutex, - statusList: std.Pair[], + mutex: std.SharedTimedMutex, + statusList: std.Pair[], ): Promise { - for (let i: number = 0; i < MAGNIFIER * 10; ++i) { - // JUST DELAY FOR SAFETY - await std.sleep_for(100); - const time: number = Date.now(); + for (let i: number = 0; i < MAGNIFIER * 10; ++i) { + // JUST DELAY FOR SAFETY + await std.sleep_for(100); + const time: number = Date.now(); - // DO WRITE - await mutex.lock(); - { - const now: number = Date.now(); - statusList.push(new std.Pair(Status.START_WRITING, now - time)); + // DO WRITE + await mutex.lock(); + { + const now: number = Date.now(); + statusList.push(new std.Pair(Status.START_WRITING, now - time)); - await std.sleep_for(50); - statusList.push(new std.Pair(Status.END_WRITING, Date.now() - now)); - } - await mutex.unlock(); + await std.sleep_for(50); + statusList.push(new std.Pair(Status.END_WRITING, Date.now() - now)); } + await mutex.unlock(); + } } async function read( - mutex: std.SharedTimedMutex, - statusList: std.Pair[], + mutex: std.SharedTimedMutex, + statusList: std.Pair[], ): Promise { - for (let i: number = 0; i < MAGNIFIER * 100; ++i) { - const time: number = Date.now(); + for (let i: number = 0; i < MAGNIFIER * 100; ++i) { + const time: number = Date.now(); - // DO READ - await mutex.lock_shared(); - { - const now: number = Date.now(); - statusList.push(new std.Pair(Status.START_READING, now - time)); + // DO READ + await mutex.lock_shared(); + { + const now: number = Date.now(); + statusList.push(new std.Pair(Status.START_READING, now - time)); - await std.sleep_for(10); - statusList.push(new std.Pair(Status.END_READING, Date.now() - now)); - } - await mutex.unlock_shared(); + await std.sleep_for(10); + statusList.push(new std.Pair(Status.END_READING, Date.now() - now)); } + await mutex.unlock_shared(); + } } export async function test_shared_mutexes(): Promise { - const mutex: std.SharedTimedMutex = new std.SharedTimedMutex(); - const statusList: std.Pair[] = []; + const mutex: std.SharedTimedMutex = new std.SharedTimedMutex(); + const statusList: std.Pair[] = []; - try { - const promises: Promise[] = []; - for (let i: number = 0; i < 25; ++i) - promises.push(read(mutex, statusList)); - promises.push(write(mutex, statusList)); + try { + const promises: Promise[] = []; + for (let i: number = 0; i < 25; ++i) promises.push(read(mutex, statusList)); + promises.push(write(mutex, statusList)); - await Promise.all(promises); + await Promise.all(promises); - let reading: number = 0; - let writing: number = 0; + let reading: number = 0; + let writing: number = 0; - for (let i: number = 0; i < statusList.length; ++i) { - const status: Status = statusList[i].first; + for (let i: number = 0; i < statusList.length; ++i) { + const status: Status = statusList[i].first; - if (status === Status.START_READING) ++reading; - else if (status === Status.START_WRITING) ++writing; - else if (status === Status.END_READING) --reading; - else --writing; + if (status === Status.START_READING) ++reading; + else if (status === Status.START_WRITING) ++writing; + else if (status === Status.END_READING) --reading; + else --writing; - if (writing > 0 && reading > 0) - throw new Error( - `Bug on SharedTimeMutex; reading and writing at the same time at ${i}`, - ); - } - } catch (exp) { - for (const pair of statusList) console.log(pair.first, pair.second); - throw exp; + if (writing > 0 && reading > 0) + throw new Error( + `Bug on SharedTimeMutex; reading and writing at the same time at ${i}`, + ); } + } catch (exp) { + for (const pair of statusList) console.log(pair.first, pair.second); + throw exp; + } } diff --git a/src/test/thread/test_singleton.ts b/src/test/thread/test_singleton.ts index 91563f61..a5d4d3cf 100644 --- a/src/test/thread/test_singleton.ts +++ b/src/test/thread/test_singleton.ts @@ -1,31 +1,31 @@ import std from "../../index"; function closure( - counter: std.IPointer, - x: number, - y: number, - z: number, + counter: std.IPointer, + x: number, + y: number, + z: number, ): number { - ++counter.value; - return x + y + z; + ++counter.value; + return x + y + z; } export function test_singleton(): void { - const variadic = new std.Singleton(closure); - const counter: std.IPointer = { value: 0 }; + const variadic = new std.Singleton(closure); + const counter: std.IPointer = { value: 0 }; - for (let i: number = 0; i < 10; ++i) - for (let x: number = 0; x < 3; ++x) - for (let y: number = 0; y < 3; ++y) - for (let z: number = 0; z < 3; ++z) { - const solution: number = variadic.get(counter, x, y, z); - if (solution !== 0) - throw new Error( - "Bug on Singleton.get(): retried arguments must not afftect to the return value.", - ); - } - if (counter.value !== 1) - throw new Error( - "Bug on Singleton.get(): failed to memoize the pre-generated value.", - ); + for (let i: number = 0; i < 10; ++i) + for (let x: number = 0; x < 3; ++x) + for (let y: number = 0; y < 3; ++y) + for (let z: number = 0; z < 3; ++z) { + const solution: number = variadic.get(counter, x, y, z); + if (solution !== 0) + throw new Error( + "Bug on Singleton.get(): retried arguments must not afftect to the return value.", + ); + } + if (counter.value !== 1) + throw new Error( + "Bug on Singleton.get(): failed to memoize the pre-generated value.", + ); } diff --git a/src/test/thread/test_sleeps.ts b/src/test/thread/test_sleeps.ts index 7e8c9cf8..457f5593 100644 --- a/src/test/thread/test_sleeps.ts +++ b/src/test/thread/test_sleeps.ts @@ -1,32 +1,32 @@ import * as std from "../../index"; export async function test_sleeps(): Promise { - await _Test_sleep_for(); - await _Test_sleep_until(); + await _Test_sleep_for(); + await _Test_sleep_until(); } async function _Test_sleep_for(): Promise { - // RECORD TIMEPOINTS DURING SLEEP_FOR - const t1 = new Date(); - await std.sleep_for(50); - const t2 = new Date(); + // RECORD TIMEPOINTS DURING SLEEP_FOR + const t1 = new Date(); + await std.sleep_for(50); + const t2 = new Date(); - // VALIDATE THE SLEEP_FOR - _Validate_sleep(t1, t2); + // VALIDATE THE SLEEP_FOR + _Validate_sleep(t1, t2); } async function _Test_sleep_until(): Promise { - // RECORD TIMEPOINTS DURING SLEEP_FOR - const t1 = new Date(); - await std.sleep_until(new Date(t1.getTime() + 50)); - const t2 = new Date(); + // RECORD TIMEPOINTS DURING SLEEP_FOR + const t1 = new Date(); + await std.sleep_until(new Date(t1.getTime() + 50)); + const t2 = new Date(); - // VAIDATE THE SLEEP_UNTIL - _Validate_sleep(t1, t2); + // VAIDATE THE SLEEP_UNTIL + _Validate_sleep(t1, t2); } function _Validate_sleep(t1: Date, t2: Date): void { - const ms: number = t2.getTime() - t1.getTime(); - if (ms < 50 * 0.5 || ms >= 50 * 1.5) - throw new Error(`Bug on sleep_for(): ${ms}`); + const ms: number = t2.getTime() - t1.getTime(); + if (ms < 50 * 0.5 || ms >= 50 * 1.5) + throw new Error(`Bug on sleep_for(): ${ms}`); } diff --git a/src/test/thread/test_timed_singleton.ts b/src/test/thread/test_timed_singleton.ts index 26c0f53b..eadb41a2 100644 --- a/src/test/thread/test_timed_singleton.ts +++ b/src/test/thread/test_timed_singleton.ts @@ -1,12 +1,12 @@ import std from "../../index"; export async function test_timed_singleton(): Promise { - let i: number = 0; - const singleton = new std.TimedSingleton(10, () => i); - singleton.get(); + let i: number = 0; + const singleton = new std.TimedSingleton(10, () => i); + singleton.get(); - await std.sleep_for(20); - ++i; - if (singleton.get() !== 1) - throw new Error("Bug on TimedSingleton.get(): not re-constructed."); + await std.sleep_for(20); + ++i; + if (singleton.get() !== 1) + throw new Error("Bug on TimedSingleton.get(): not re-constructed."); } diff --git a/src/test/thread/test_variadic_mutable_singleton.ts b/src/test/thread/test_variadic_mutable_singleton.ts index 35c89382..3011b1ca 100644 --- a/src/test/thread/test_variadic_mutable_singleton.ts +++ b/src/test/thread/test_variadic_mutable_singleton.ts @@ -1,36 +1,31 @@ import std from "../../index"; async function closure( - counter: std.IPointer, - x: number, - y: number, - z: number, + counter: std.IPointer, + x: number, + y: number, + z: number, ): Promise { - ++counter.value; - return x + y + z; + ++counter.value; + return x + y + z; } export async function test_variadic_mutable_singleton(): Promise { - const variadic = new std.VariadicMutableSingleton(closure); - const counter: std.IPointer = { value: 0 }; + const variadic = new std.VariadicMutableSingleton(closure); + const counter: std.IPointer = { value: 0 }; - for (let i: number = 0; i < 10; ++i) - for (let x: number = 0; x < 3; ++x) - for (let y: number = 0; y < 3; ++y) - for (let z: number = 0; z < 3; ++z) { - const solution: number = await variadic.get( - counter, - x, - y, - z, - ); - if (solution !== x + y + z) - throw new Error( - "Bug on VariadicMutableSingleton.get(): failed to detect the different arguments.", - ); - } - if (counter.value !== 27) - throw new Error( - "Bug on VariadicMutableSingleton.get(): failed to memoize the pre-generated value.", - ); + for (let i: number = 0; i < 10; ++i) + for (let x: number = 0; x < 3; ++x) + for (let y: number = 0; y < 3; ++y) + for (let z: number = 0; z < 3; ++z) { + const solution: number = await variadic.get(counter, x, y, z); + if (solution !== x + y + z) + throw new Error( + "Bug on VariadicMutableSingleton.get(): failed to detect the different arguments.", + ); + } + if (counter.value !== 27) + throw new Error( + "Bug on VariadicMutableSingleton.get(): failed to memoize the pre-generated value.", + ); } diff --git a/src/test/thread/test_variadic_singleton.ts b/src/test/thread/test_variadic_singleton.ts index d748218a..c586ace3 100644 --- a/src/test/thread/test_variadic_singleton.ts +++ b/src/test/thread/test_variadic_singleton.ts @@ -1,31 +1,31 @@ import std from "../../index"; function closure( - counter: std.IPointer, - x: number, - y: number, - z: number, + counter: std.IPointer, + x: number, + y: number, + z: number, ): number { - ++counter.value; - return x + y + z; + ++counter.value; + return x + y + z; } export function test_variadic_singleton(): void { - const variadic = new std.VariadicSingleton(closure); - const counter: std.IPointer = { value: 0 }; + const variadic = new std.VariadicSingleton(closure); + const counter: std.IPointer = { value: 0 }; - for (let i: number = 0; i < 10; ++i) - for (let x: number = 0; x < 3; ++x) - for (let y: number = 0; y < 3; ++y) - for (let z: number = 0; z < 3; ++z) { - const solution: number = variadic.get(counter, x, y, z); - if (solution !== x + y + z) - throw new Error( - "Bug on VariadicSingleton.get(): failed to detect the different arguments.", - ); - } - if (counter.value !== 27) - throw new Error( - "Bug on VariadicSingleton.get(): failed to memoize the pre-generated value.", - ); + for (let i: number = 0; i < 10; ++i) + for (let x: number = 0; x < 3; ++x) + for (let y: number = 0; y < 3; ++y) + for (let z: number = 0; z < 3; ++z) { + const solution: number = variadic.get(counter, x, y, z); + if (solution !== x + y + z) + throw new Error( + "Bug on VariadicSingleton.get(): failed to detect the different arguments.", + ); + } + if (counter.value !== 27) + throw new Error( + "Bug on VariadicSingleton.get(): failed to memoize the pre-generated value.", + ); } diff --git a/src/test/utility/test_utilities.ts b/src/test/utility/test_utilities.ts index abc77dab..9c550d26 100644 --- a/src/test/utility/test_utilities.ts +++ b/src/test/utility/test_utilities.ts @@ -1,22 +1,22 @@ import * as std from "../../index"; export function test_utilities() { - _Test_pairs(); - _Test_node(); + _Test_pairs(); + _Test_node(); } function _Test_pairs(): void { - const x = std.make_pair(1, 2); - const y = std.make_pair(1, 2); - const z = std.make_pair(1, 3); + const x = std.make_pair(1, 2); + const y = std.make_pair(1, 2); + const z = std.make_pair(1, 3); - if (x.hashCode() !== y.hashCode() || x.hashCode() === z.hashCode()) - throw new Error("Bug on Pair.hashCode()"); - else if (x.equals(y) === false || x.equals(z) === true) - throw new Error("Bug on Pair.equals()"); + if (x.hashCode() !== y.hashCode() || x.hashCode() === z.hashCode()) + throw new Error("Bug on Pair.hashCode()"); + else if (x.equals(y) === false || x.equals(z) === true) + throw new Error("Bug on Pair.equals()"); } function _Test_node(): void { - if (std.is_node() === false) - throw new Error("Bug on is_node(): wrong result"); + if (std.is_node() === false) + throw new Error("Bug on is_node(): wrong result"); } diff --git a/src/thread/Barrier.ts b/src/thread/Barrier.ts index 4e9efd94..65e5802c 100644 --- a/src/thread/Barrier.ts +++ b/src/thread/Barrier.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -16,110 +17,110 @@ import { ConditionVariable } from "./ConditionVariable"; * @author Jeongho Nam - https://github.com/samchon */ export class Barrier { - private cv_: ConditionVariable; + private cv_: ConditionVariable; - private size_: number; - private count_: number; + private size_: number; + private count_: number; - /** - * Initializer Constructor - * - * @param size Size of the downward counter. - */ - public constructor(size: number) { - this.cv_ = new ConditionVariable(); + /** + * Initializer Constructor + * + * @param size Size of the downward counter. + */ + public constructor(size: number) { + this.cv_ = new ConditionVariable(); - this.size_ = size; - this.count_ = size; - } + this.size_ = size; + this.count_ = size; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- WAIT FUNCTIONS --------------------------------------------------------- */ - /** - * Waits until the counter to be zero. - * - * Blocks the function calling until internal counter to be reached to the zero. - */ - public wait(): Promise { - return this.cv_.wait(); - } + /** + * Waits until the counter to be zero. + * + * Blocks the function calling until internal counter to be reached to the zero. + */ + public wait(): Promise { + return this.cv_.wait(); + } - /** - * Tries to wait until the counter to be zero in timeout. - * - * Attempts to block the function calling until internal counter to be reached to the zero - * in timeout. If succeeded to waiting the counter to be reached to the zero, it returns - * `true`. Otherwise, the {@link Barrier} fails to reach to the zero in the given time, the - * function gives up the waiting and returns `false`. - * - * @param ms The maximum miliseconds for waiting. - * @return Whether succeeded to waiting in the given time. - */ - public wait_for(ms: number): Promise { - return this.cv_.wait_for(ms); - } + /** + * Tries to wait until the counter to be zero in timeout. + * + * Attempts to block the function calling until internal counter to be reached to the zero + * in timeout. If succeeded to waiting the counter to be reached to the zero, it returns + * `true`. Otherwise, the {@link Barrier} fails to reach to the zero in the given time, the + * function gives up the waiting and returns `false`. + * + * @param ms The maximum miliseconds for waiting. + * @return Whether succeeded to waiting in the given time. + */ + public wait_for(ms: number): Promise { + return this.cv_.wait_for(ms); + } - /** - * Tries to wait until the counter to be zero in time expiration. - * - * Attempts to block the function calling until internal counter to be reached to the zero - * in time expiration. If succeeded to waiting the counter to be reached to the zero, it - * returns `true`. Otherwise, the {@link Barrier} fails to reach to the zero in the given - * time, the function gives up the waiting and returns `false`. - * - * @param at The maximum time point to wait. - * @return Whether succeeded to waiting in the given time. - */ - public wait_until(at: Date): Promise { - return this.cv_.wait_until(at); - } + /** + * Tries to wait until the counter to be zero in time expiration. + * + * Attempts to block the function calling until internal counter to be reached to the zero + * in time expiration. If succeeded to waiting the counter to be reached to the zero, it + * returns `true`. Otherwise, the {@link Barrier} fails to reach to the zero in the given + * time, the function gives up the waiting and returns `false`. + * + * @param at The maximum time point to wait. + * @return Whether succeeded to waiting in the given time. + */ + public wait_until(at: Date): Promise { + return this.cv_.wait_until(at); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ARRIVAL FUNCTIONS --------------------------------------------------------- */ - /** - * Derecements the counter. - * - * Decrements the counter by *n* without blocking. - * - * If the parametric value *n* is equal to or greater than internal counter, so that the - * internal counter be equal to or less than zero, everyone who are {@link wait waiting} for - * the {@link Latch} would continue their executions. - * - * @param n Value of the decrement. Default is 1. - */ - public async arrive(n: number = 1): Promise { - const completed: boolean = (this.count_ += n) <= this.size_; - if (completed === false) return; + /** + * Derecements the counter. + * + * Decrements the counter by *n* without blocking. + * + * If the parametric value *n* is equal to or greater than internal counter, so that the + * internal counter be equal to or less than zero, everyone who are {@link wait waiting} for + * the {@link Latch} would continue their executions. + * + * @param n Value of the decrement. Default is 1. + */ + public async arrive(n: number = 1): Promise { + const completed: boolean = (this.count_ += n) <= this.size_; + if (completed === false) return; - this.count_ %= this.size_; - await this.cv_.notify_all(); - } + this.count_ %= this.size_; + await this.cv_.notify_all(); + } - /** - * Decrements the counter and waits until the counter to be zero. - * - * Decrements the counter by one and blocks the section until internal counter to be zero. - * - * If the the remained counter be zero by this decrement, everyone who are - * {@link wait waiting} for the {@link Barrier} would continue their executions including - * this one. - */ - public async arrive_and_wait(): Promise { - await this.arrive(); - await this.wait(); - } + /** + * Decrements the counter and waits until the counter to be zero. + * + * Decrements the counter by one and blocks the section until internal counter to be zero. + * + * If the the remained counter be zero by this decrement, everyone who are + * {@link wait waiting} for the {@link Barrier} would continue their executions including + * this one. + */ + public async arrive_and_wait(): Promise { + await this.arrive(); + await this.wait(); + } - /** - * Decrements the counter and initial size at the same time. - * - * Decrements not only internal counter, but also initialize size of the counter at the same - * time. If the remained counter be zero by the decrement, everyone who are - * {@link wait waiting} for the {@link Barrier} would continue their executions. - */ - public async arrive_and_drop(): Promise { - --this.size_; - await this.arrive(0); - } + /** + * Decrements the counter and initial size at the same time. + * + * Decrements not only internal counter, but also initialize size of the counter at the same + * time. If the remained counter be zero by the decrement, everyone who are + * {@link wait waiting} for the {@link Barrier} would continue their executions. + */ + public async arrive_and_drop(): Promise { + --this.size_; + await this.arrive(0); + } } diff --git a/src/thread/ConditionVariable.ts b/src/thread/ConditionVariable.ts index 3215a56d..7348f73f 100644 --- a/src/thread/ConditionVariable.ts +++ b/src/thread/ConditionVariable.ts @@ -1,13 +1,13 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ import { List } from "../container/List"; -import { sleep_until } from "./global"; - import { LockType } from "../internal/thread/LockType"; +import { sleep_until } from "./global"; /** * Condition variable. @@ -17,27 +17,27 @@ import { LockType } from "../internal/thread/LockType"; * @author Jeongho Nam - https://github.com/samchon */ export class ConditionVariable { - private resolvers_: List; + private resolvers_: List; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor() { - this.resolvers_ = new List(); - } - - /* --------------------------------------------------------- + /** + * Default Constructor. + */ + public constructor() { + this.resolvers_ = new List(); + } + + /* --------------------------------------------------------- WAIT FUNCTIONS --------------------------------------------------------- */ - /** - * Wait until notified. - */ - public wait(): Promise; + /** + * Wait until notified. + */ + public wait(): Promise; - /** + /** * Wait until predicator returns true. * * This method is equivalent to: @@ -49,25 +49,23 @@ export class ConditionVariable { * * @param predicator A predicator function determines completion. */ - public wait(predicator: ConditionVariable.Predicator): Promise; + public wait(predicator: ConditionVariable.Predicator): Promise; - public async wait( - predicator?: ConditionVariable.Predicator, - ): Promise { - if (!predicator) return await this._Wait(); + public async wait(predicator?: ConditionVariable.Predicator): Promise { + if (!predicator) return await this._Wait(); - while (!(await predicator())) await this._Wait(); - } + while (!(await predicator())) await this._Wait(); + } - /** - * Wait for timeout or until notified. - * - * @param ms The maximum miliseconds for waiting. - * @return Whether awaken by notification or timeout. - */ - public wait_for(ms: number): Promise; + /** + * Wait for timeout or until notified. + * + * @param ms The maximum miliseconds for waiting. + * @return Whether awaken by notification or timeout. + */ + public wait_for(ms: number): Promise; - /** + /** * Wait until timeout or predicator returns true. * * This method is equivalent to: @@ -85,28 +83,28 @@ export class ConditionVariable { * @param predicator A predicator function determines the completion. * @return Returned value of the *predicator*. */ - public wait_for( - ms: number, - predicator: ConditionVariable.Predicator, - ): Promise; - - public wait_for( - ms: number, - predicator?: ConditionVariable.Predicator, - ): Promise { - const at: Date = new Date(Date.now() + ms); - return this.wait_until(at, predicator!); - } - - /** - * Wait until notified or time expiration. - * - * @param at The maximum time point to wait. - * @return Whether awaken by notification or time expiration. - */ - public wait_until(at: Date): Promise; - - /** + public wait_for( + ms: number, + predicator: ConditionVariable.Predicator, + ): Promise; + + public wait_for( + ms: number, + predicator?: ConditionVariable.Predicator, + ): Promise { + const at: Date = new Date(Date.now() + ms); + return this.wait_until(at, predicator!); + } + + /** + * Wait until notified or time expiration. + * + * @param at The maximum time point to wait. + * @return Whether awaken by notification or time expiration. + */ + public wait_until(at: Date): Promise; + + /** * Wait until time expiration or predicator returns true. * * This method is equivalent to: @@ -123,101 +121,101 @@ export class ConditionVariable { * @param predicator A predicator function determines the completion. * @return Returned value of the *predicator*. */ - public wait_until( - at: Date, - predicator: ConditionVariable.Predicator, - ): Promise; - - public async wait_until( - at: Date, - predicator?: ConditionVariable.Predicator, - ): Promise { - if (!predicator) return await this._Wait_until(at); - - while (!(await predicator())) - if (!(await this._Wait_until(at))) return await predicator(); - - return true; - } + public wait_until( + at: Date, + predicator: ConditionVariable.Predicator, + ): Promise; - private _Wait(): Promise { - return new Promise((resolve) => { - this.resolvers_.push_back({ - handler: resolve, - lockType: LockType.HOLD, - }); - }); - } + public async wait_until( + at: Date, + predicator?: ConditionVariable.Predicator, + ): Promise { + if (!predicator) return await this._Wait_until(at); - private _Wait_until(at: Date): Promise { - return new Promise((resolve) => { - const it: List.Iterator = this.resolvers_.insert( - this.resolvers_.end(), - { - handler: resolve, - lockType: LockType.KNOCK, - }, - ); - - // AUTOMATIC UNLOCK - sleep_until(at).then(() => { - if (it.erased_ === true) return; - - // DO UNLOCK - this.resolvers_.erase(it); // POP THE LISTENER - resolve(false); // RETURN FAILURE - }); - }); - } + while (!(await predicator())) + if (!(await this._Wait_until(at))) return await predicator(); - /* --------------------------------------------------------- + return true; + } + + private _Wait(): Promise { + return new Promise((resolve) => { + this.resolvers_.push_back({ + handler: resolve, + lockType: LockType.HOLD, + }); + }); + } + + private _Wait_until(at: Date): Promise { + return new Promise((resolve) => { + const it: List.Iterator = this.resolvers_.insert( + this.resolvers_.end(), + { + handler: resolve, + lockType: LockType.KNOCK, + }, + ); + + // AUTOMATIC UNLOCK + sleep_until(at).then(() => { + if (it.erased_ === true) return; + + // DO UNLOCK + this.resolvers_.erase(it); // POP THE LISTENER + resolve(false); // RETURN FAILURE + }); + }); + } + + /* --------------------------------------------------------- NOTIFIERS --------------------------------------------------------- */ - /** - * Notify, wake only one up. - */ - public async notify_one(): Promise { - // NOTHING TO NOTIFY - if (this.resolvers_.empty()) return; - - // POP THE 1ST RESOLVER - const it = this.resolvers_.begin(); - this.resolvers_.erase(it); - - // CALL ITS HANDLER - if (it.value.lockType === LockType.HOLD) it.value.handler(); - else it.value.handler(true); - } - - /** - * Notify, wake all up. - */ - public async notify_all(): Promise { - // NOTHING TO NOTIFY - if (this.resolvers_.empty()) return; - - // POP RESOLVERS - const resolverList: IResolver[] = this.resolvers_.toJSON(); - this.resolvers_.clear(); - - // ITERATE RESOLVERS - for (const resolver of resolverList) - if (resolver.lockType === LockType.HOLD) resolver.handler(); - else resolver.handler(true); - } + /** + * Notify, wake only one up. + */ + public async notify_one(): Promise { + // NOTHING TO NOTIFY + if (this.resolvers_.empty()) return; + + // POP THE 1ST RESOLVER + const it = this.resolvers_.begin(); + this.resolvers_.erase(it); + + // CALL ITS HANDLER + if (it.value.lockType === LockType.HOLD) it.value.handler(); + else it.value.handler(true); + } + + /** + * Notify, wake all up. + */ + public async notify_all(): Promise { + // NOTHING TO NOTIFY + if (this.resolvers_.empty()) return; + + // POP RESOLVERS + const resolverList: IResolver[] = this.resolvers_.toJSON(); + this.resolvers_.clear(); + + // ITERATE RESOLVERS + for (const resolver of resolverList) + if (resolver.lockType === LockType.HOLD) resolver.handler(); + else resolver.handler(true); + } } /** * */ export namespace ConditionVariable { - /** - * Type of predicator function who determines the completion. - */ - export type Predicator = () => boolean | Promise; + /** + * Type of predicator function who determines the completion. + */ + export type Predicator = () => boolean | Promise; } interface IResolver { - handler: (value?: any) => void; - lockType: LockType; + handler: (value?: any) => void; + lockType: LockType; } diff --git a/src/thread/Latch.ts b/src/thread/Latch.ts index d62d16f4..6ab7f746 100644 --- a/src/thread/Latch.ts +++ b/src/thread/Latch.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -16,121 +17,121 @@ import { ConditionVariable } from "./ConditionVariable"; * @author Jeongho Nam - https://github.com/samchon */ export class Latch { - private cv_: ConditionVariable; - private count_: number; + private cv_: ConditionVariable; + private count_: number; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * @param size Size of the downward counter. - */ - public constructor(size: number) { - this.cv_ = new ConditionVariable(); - this.count_ = size; - } + /** + * Initializer Constructor. + * + * @param size Size of the downward counter. + */ + public constructor(size: number) { + this.cv_ = new ConditionVariable(); + this.count_ = size; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- WAIT FUNCTIONS --------------------------------------------------------- */ - /** - * Waits until the counter to be zero. - * - * Blocks the function calling until internal counter to be reached to the zero. - * - * If the {@link Latch} already has been reached to the zero, it would be returned - * immediately. - */ - public async wait(): Promise { - if (this._Try_wait() === false) await this.cv_.wait(); - } + /** + * Waits until the counter to be zero. + * + * Blocks the function calling until internal counter to be reached to the zero. + * + * If the {@link Latch} already has been reached to the zero, it would be returned + * immediately. + */ + public async wait(): Promise { + if (this._Try_wait() === false) await this.cv_.wait(); + } - /** - * Test whether the counter has been reached to the zero. - * - * The {@link try_wait} function tests whether the internal counter has been reached to the - * zero. - * - * @return Whether reached to zero or not. - */ - public async try_wait(): Promise { - return this._Try_wait(); - } + /** + * Test whether the counter has been reached to the zero. + * + * The {@link try_wait} function tests whether the internal counter has been reached to the + * zero. + * + * @return Whether reached to zero or not. + */ + public async try_wait(): Promise { + return this._Try_wait(); + } - /** - * Tries to wait until the counter to be zero in timeout. - * - * Attempts to block the function calling until internal counter to be reached to the zero - * in timeout. If succeeded to waiting the counter to be reached to the zero, it returns - * `true`. Otherwise, the {@link Latch} fails to reach to the zero in the given time, the - * function gives up the waiting and returns `false`. - * - * If the {@link Latch} already has been reached to the zero, it would return `true` directly. - * - * @param ms The maximum miliseconds for waiting. - * @return Whether succeeded to waiting in the given time. - */ - public async wait_for(ms: number): Promise { - if (this._Try_wait() === true) return true; - else return await this.cv_.wait_for(ms); - } + /** + * Tries to wait until the counter to be zero in timeout. + * + * Attempts to block the function calling until internal counter to be reached to the zero + * in timeout. If succeeded to waiting the counter to be reached to the zero, it returns + * `true`. Otherwise, the {@link Latch} fails to reach to the zero in the given time, the + * function gives up the waiting and returns `false`. + * + * If the {@link Latch} already has been reached to the zero, it would return `true` directly. + * + * @param ms The maximum miliseconds for waiting. + * @return Whether succeeded to waiting in the given time. + */ + public async wait_for(ms: number): Promise { + if (this._Try_wait() === true) return true; + else return await this.cv_.wait_for(ms); + } - /** - * Tries to wait until the counter to be zero in time expiration. - * - * Attempts to block the function calling until internal counter to be reached to the zero - * in time expiration. If succeeded to waiting the counter to be reached to the zero, it - * returns `true`. Otherwise, the {@link Latch} fails to reach to the zero in the given time, - * the function gives up the waiting and returns `false`. - * - * If the {@link Latch} already has been reached to the zero, it would return `true` directly. - * - * @param at The maximum time point to wait. - * @return Whether succeeded to waiting in the given time. - */ - public async wait_until(at: Date): Promise { - if (this._Try_wait() === true) return true; - else return await this.cv_.wait_until(at); - } + /** + * Tries to wait until the counter to be zero in time expiration. + * + * Attempts to block the function calling until internal counter to be reached to the zero + * in time expiration. If succeeded to waiting the counter to be reached to the zero, it + * returns `true`. Otherwise, the {@link Latch} fails to reach to the zero in the given time, + * the function gives up the waiting and returns `false`. + * + * If the {@link Latch} already has been reached to the zero, it would return `true` directly. + * + * @param at The maximum time point to wait. + * @return Whether succeeded to waiting in the given time. + */ + public async wait_until(at: Date): Promise { + if (this._Try_wait() === true) return true; + else return await this.cv_.wait_until(at); + } - private _Try_wait(): boolean { - return this.count_ <= 0; - } + private _Try_wait(): boolean { + return this.count_ <= 0; + } - /* ----------------------------------------------------------- + /* ----------------------------------------------------------- ARRIVAL FUNCTIONS ----------------------------------------------------------- */ - /** - * Derecements the counter. - * - * Decrements the counter by *n* without blocking. - * - * If the parametric value *n* is equal to or greater than internal counter, so that the - * internal counter be equal to or less than zero, everyone who are {@link wait waiting} for - * the {@link Latch} would continue their execution. - * - * @param n Value of the decrement. Default is 1. - */ - public async count_down(n: number = 1): Promise { - this.count_ -= n; - if (this._Try_wait() === true) await this.cv_.notify_all(); - } + /** + * Derecements the counter. + * + * Decrements the counter by *n* without blocking. + * + * If the parametric value *n* is equal to or greater than internal counter, so that the + * internal counter be equal to or less than zero, everyone who are {@link wait waiting} for + * the {@link Latch} would continue their execution. + * + * @param n Value of the decrement. Default is 1. + */ + public async count_down(n: number = 1): Promise { + this.count_ -= n; + if (this._Try_wait() === true) await this.cv_.notify_all(); + } - /** - * Decrements the counter and waits until the counter to be zero. - * - * Decrements the counter by *n* and blocks the section until internal counter to be zero. - * - * If the parametric value *n* is equal to or greater than internal counter, so that the - * internal counter be equal to or less than zero, everyone who are {@link wait waiting} for - * the {@link Latch} would continue their execution including this one. - * - * @param n Value of the decrement. Default is 1. - */ - public async arrive_and_wait(n: number = 1): Promise { - await this.count_down(n); - await this.wait(); - } + /** + * Decrements the counter and waits until the counter to be zero. + * + * Decrements the counter by *n* and blocks the section until internal counter to be zero. + * + * If the parametric value *n* is equal to or greater than internal counter, so that the + * internal counter be equal to or less than zero, everyone who are {@link wait waiting} for + * the {@link Latch} would continue their execution including this one. + * + * @param n Value of the decrement. Default is 1. + */ + public async arrive_and_wait(n: number = 1): Promise { + await this.count_down(n); + await this.wait(); + } } diff --git a/src/thread/MutableSingleton.ts b/src/thread/MutableSingleton.ts index 88cab1b0..0c1aea33 100644 --- a/src/thread/MutableSingleton.ts +++ b/src/thread/MutableSingleton.ts @@ -1,11 +1,12 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { SharedMutex } from "./SharedMutex"; import { SharedLock } from "./SharedLock"; +import { SharedMutex } from "./SharedMutex"; import { UniqueLock } from "./UniqueLock"; /** @@ -33,143 +34,143 @@ import { UniqueLock } from "./UniqueLock"; * @author Jeongho Nam - https://github.com/samchon */ export class MutableSingleton { - /** - * @hidden - */ - private readonly closure_: (...args: Args) => Promise; + /** + * @hidden + */ + private readonly closure_: (...args: Args) => Promise; - /** - * @hidden - */ - private readonly mutex_: SharedMutex; + /** + * @hidden + */ + private readonly mutex_: SharedMutex; - /** - * @hidden - */ - private value_: T | object; + /** + * @hidden + */ + private value_: T | object; - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * Create a new `Singleton` instance with the *lazy consturctor*. - * - * @param closure Lazy constructor function returning the promised value. - */ - public constructor(closure: (...args: Args) => Promise) { - this.closure_ = closure; - this.mutex_ = new SharedMutex(); - this.value_ = NOT_MOUNTED_YET; - } + /** + * Initializer Constructor. + * + * Create a new `Singleton` instance with the *lazy consturctor*. + * + * @param closure Lazy constructor function returning the promised value. + */ + public constructor(closure: (...args: Args) => Promise) { + this.closure_ = closure; + this.mutex_ = new SharedMutex(); + this.value_ = NOT_MOUNTED_YET; + } - /** - * Reload value. - * - * The `MutableSingleton.reload()` method enforces to call the *lazy constructor*, regardless - * of whether the *lazy construction* has been completed or not. Therefore, even if the *lazy - * construction* has been completed in sometime, the `MutableSingleton.reload()` will call - * the *lazy constructor* again. - * - * @return Re-constructed value. - */ - public async reload(...args: Args): Promise { - let output: T; - await UniqueLock.lock(this.mutex_, async () => { - output = await this.closure_(...args); - this.value_ = output; - }); - return output!; - } + /** + * Reload value. + * + * The `MutableSingleton.reload()` method enforces to call the *lazy constructor*, regardless + * of whether the *lazy construction* has been completed or not. Therefore, even if the *lazy + * construction* has been completed in sometime, the `MutableSingleton.reload()` will call + * the *lazy constructor* again. + * + * @return Re-constructed value. + */ + public async reload(...args: Args): Promise { + let output: T; + await UniqueLock.lock(this.mutex_, async () => { + output = await this.closure_(...args); + this.value_ = output; + }); + return output!; + } - /** - * Configure value. - * - * The `MutableSingleton.set()` method enforces the singleton to have a specific value. - * - * @param value The value to configure - */ - public async set(value: T): Promise { - await UniqueLock.lock(this.mutex_, () => { - this.value_ = value; - }); - } + /** + * Configure value. + * + * The `MutableSingleton.set()` method enforces the singleton to have a specific value. + * + * @param value The value to configure + */ + public async set(value: T): Promise { + await UniqueLock.lock(this.mutex_, () => { + this.value_ = value; + }); + } - /** - * Clear value. - * - * The `MutableSingleton.clear()` is a method clearing cached value. - * - * Therefore, when {@link get} being called, closure of constructor would be reused. - */ - public async clear(): Promise { - await UniqueLock.lock(this.mutex_, () => { - this.value_ = NOT_MOUNTED_YET; - }); - } + /** + * Clear value. + * + * The `MutableSingleton.clear()` is a method clearing cached value. + * + * Therefore, when {@link get} being called, closure of constructor would be reused. + */ + public async clear(): Promise { + await UniqueLock.lock(this.mutex_, () => { + this.value_ = NOT_MOUNTED_YET; + }); + } - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- ACCESSORS --------------------------------------------------------------- */ - /** - * Get promised value. - * - * `MutableSingleton.get()` method returns the *lazy constructed value*. It guarantees the - * *lazy constructor* to be called *"only one at time"*. It ensures the *"only one at time"*, - * even in the race condition. - * - * If the promised value is not constructed yet (call this method at the first time), the - * *lazy constructor* would be called and returns the promised value. Otherwise, the promised - * value has been already constructed by the *lazy constructor* (this method already had been - * called), returns the pre-generated value. - * - * Also, you don't need to worry anything about the race condition, who may be occured by - * calling the `MutableSingleton.get()` method simultaneously during the *lazy construction* - * is on going. The `MutableSingleton` guarantees the *lazy constructor* to be called - * only one at time by using the {@link UniqueLock.lock} on a {@link Mutex}. - * - * @return The *lazy constructed* value. - */ - public async get(...args: Args): Promise { - let output: T | object = NOT_MOUNTED_YET as any; - await SharedLock.lock(this.mutex_, async () => { - output = this.value_; - }); + /** + * Get promised value. + * + * `MutableSingleton.get()` method returns the *lazy constructed value*. It guarantees the + * *lazy constructor* to be called *"only one at time"*. It ensures the *"only one at time"*, + * even in the race condition. + * + * If the promised value is not constructed yet (call this method at the first time), the + * *lazy constructor* would be called and returns the promised value. Otherwise, the promised + * value has been already constructed by the *lazy constructor* (this method already had been + * called), returns the pre-generated value. + * + * Also, you don't need to worry anything about the race condition, who may be occured by + * calling the `MutableSingleton.get()` method simultaneously during the *lazy construction* + * is on going. The `MutableSingleton` guarantees the *lazy constructor* to be called + * only one at time by using the {@link UniqueLock.lock} on a {@link Mutex}. + * + * @return The *lazy constructed* value. + */ + public async get(...args: Args): Promise { + let output: T | object = NOT_MOUNTED_YET as any; + await SharedLock.lock(this.mutex_, async () => { + output = this.value_; + }); - if (output === NOT_MOUNTED_YET) - await UniqueLock.lock(this.mutex_, async () => { - // COULD BE COMPLETED DURING WAITING - if (this.value_ !== NOT_MOUNTED_YET) { - output = this.value_; - return; - } + if (output === NOT_MOUNTED_YET) + await UniqueLock.lock(this.mutex_, async () => { + // COULD BE COMPLETED DURING WAITING + if (this.value_ !== NOT_MOUNTED_YET) { + output = this.value_; + return; + } - // CALL THE LAZY-CONSTRUCTOR - output = await this.closure_(...args); - this.value_ = output; - }); - return output as T; - } + // CALL THE LAZY-CONSTRUCTOR + output = await this.closure_(...args); + this.value_ = output; + }); + return output as T; + } - /** - * Test whether the value has been loaded. - * - * The `MutableSingleton.is_loaded()` method tests whether the singleton has coompleted to - * constructing its value or not. If the singleton value is on the construction by the - * {@link MutableSingleton.get} or {@link MutableSingleton.reload} method, the - * `MutableSingleton.is_loaded()` would wait returning value until the construction has been - * completed. - * - * @returns Whether loaded or not - */ - public async is_loaded(): Promise { - let loaded: boolean = false; - await SharedLock.lock(this.mutex_, async () => { - loaded = this.value_ !== NOT_MOUNTED_YET; - }); - return loaded; - } + /** + * Test whether the value has been loaded. + * + * The `MutableSingleton.is_loaded()` method tests whether the singleton has coompleted to + * constructing its value or not. If the singleton value is on the construction by the + * {@link MutableSingleton.get} or {@link MutableSingleton.reload} method, the + * `MutableSingleton.is_loaded()` would wait returning value until the construction has been + * completed. + * + * @returns Whether loaded or not + */ + public async is_loaded(): Promise { + let loaded: boolean = false; + await SharedLock.lock(this.mutex_, async () => { + loaded = this.value_ !== NOT_MOUNTED_YET; + }); + return loaded; + } } /** diff --git a/src/thread/Mutex.ts b/src/thread/Mutex.ts index ab8479ae..7e2fb258 100644 --- a/src/thread/Mutex.ts +++ b/src/thread/Mutex.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -13,39 +14,39 @@ import { SharedTimedMutex } from "./SharedTimedMutex"; * @author Jeongho Nam - https://github.com/samchon */ export class Mutex implements ILockable { - private mutex_: SharedTimedMutex; + private mutex_: SharedTimedMutex; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor() { - this.mutex_ = new SharedTimedMutex(this); - } + /** + * Default Constructor. + */ + public constructor() { + this.mutex_ = new SharedTimedMutex(this); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- LOCK & UNLOCK --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public lock(): Promise { - return this.mutex_.lock(); - } + /** + * @inheritDoc + */ + public lock(): Promise { + return this.mutex_.lock(); + } - /** - * @inheritDoc - */ - public try_lock(): Promise { - return this.mutex_.try_lock(); - } + /** + * @inheritDoc + */ + public try_lock(): Promise { + return this.mutex_.try_lock(); + } - /** - * @inheritDoc - */ - public unlock(): Promise { - return this.mutex_.unlock(); - } + /** + * @inheritDoc + */ + public unlock(): Promise { + return this.mutex_.unlock(); + } } diff --git a/src/thread/Semaphore.ts b/src/thread/Semaphore.ts index 6718cbc3..aa77c9b5 100644 --- a/src/thread/Semaphore.ts +++ b/src/thread/Semaphore.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ +import { ITimedLockable } from "../base/thread/ITimedLockable"; import { List } from "../container/List"; import { InvalidArgument } from "../exception/InvalidArgument"; import { OutOfRange } from "../exception/OutOfRange"; - -import { ITimedLockable } from "../base/thread/ITimedLockable"; import { LockType } from "../internal/thread/LockType"; import { sleep_for } from "./global"; @@ -18,306 +18,306 @@ import { sleep_for } from "./global"; * @author Jeongho Nam - https://github.com/samchon */ export class Semaphore { - private queue_: List; - private acquiring_: number; - private max_: Max; + private queue_: List; + private acquiring_: number; + private max_: Max; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * @param max Number of maximum sections acquirable. - */ - public constructor(max: Max) { - this.queue_ = new List(); + /** + * Initializer Constructor. + * + * @param max Number of maximum sections acquirable. + */ + public constructor(max: Max) { + this.queue_ = new List(); - this.acquiring_ = 0; - this.max_ = max; - } + this.acquiring_ = 0; + this.max_ = max; + } - /** - * Get number of maximum sections lockable. - * - * @return Number of maximum sections lockable. - */ - public max(): Max { - return this.max_; - } + /** + * Get number of maximum sections lockable. + * + * @return Number of maximum sections lockable. + */ + public max(): Max { + return this.max_; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- ACQUIRANCES --------------------------------------------------------- */ - /** - * Acquires a section. - * - * Acquires a section until be {@link release released}. If all of the sections in the - * semaphore already have been acquired by others, the function call would be blocked until - * one of them returns its acquisition by calling the {@link release} method. - * - * In same reason, if you don't call the {@link release} function after you business, the - * others who want to {@link acquire} a section from the semaphore would be fall into the - * forever sleep. Therefore, never forget to calling the {@link release} function or utilize - * the {@link UniqueLock.lock} function instead with {@link Semaphore.get_lockable} to ensure - * the safety. - */ - public acquire(): Promise { - return new Promise((resolve) => { - if (this.acquiring_ < this.max_) { - ++this.acquiring_; - resolve(); - } else { - this.queue_.push_back({ - handler: resolve, - lockType: LockType.HOLD, - }); - } + /** + * Acquires a section. + * + * Acquires a section until be {@link release released}. If all of the sections in the + * semaphore already have been acquired by others, the function call would be blocked until + * one of them returns its acquisition by calling the {@link release} method. + * + * In same reason, if you don't call the {@link release} function after you business, the + * others who want to {@link acquire} a section from the semaphore would be fall into the + * forever sleep. Therefore, never forget to calling the {@link release} function or utilize + * the {@link UniqueLock.lock} function instead with {@link Semaphore.get_lockable} to ensure + * the safety. + */ + public acquire(): Promise { + return new Promise((resolve) => { + if (this.acquiring_ < this.max_) { + ++this.acquiring_; + resolve(); + } else { + this.queue_.push_back({ + handler: resolve, + lockType: LockType.HOLD, }); - } + } + }); + } - /** - * Tries to acquire a section. - * - * Attempts to acquire a section without blocking. If succeeded to acquire a section from the - * semaphore immediately, it returns `true` directly. Otherwise all of the sections in the - * semaphore are full, the function gives up the trial immediately and returns `false` - * directly. - * - * Note that, if you succeeded to acquire a section from the semaphore (returns `true) but do - * not call the {@link release} function after your business, the others who want to - * {@link acquire} a section from the semaphore would be fall into the forever sleep. - * Therefore, never forget to calling the {@link release} function or utilize the - * {@link UniqueLock.try_lock} function instead with {@link Semaphore.get_lockable} to ensure - * the safety. - * - * @return Whether succeeded to acquire or not. - */ - public async try_acquire(): Promise { - // ALL OR NOTHING - if (this.acquiring_ < this.max_) { - ++this.acquiring_; - return true; - } else return false; - } + /** + * Tries to acquire a section. + * + * Attempts to acquire a section without blocking. If succeeded to acquire a section from the + * semaphore immediately, it returns `true` directly. Otherwise all of the sections in the + * semaphore are full, the function gives up the trial immediately and returns `false` + * directly. + * + * Note that, if you succeeded to acquire a section from the semaphore (returns `true) but do + * not call the {@link release} function after your business, the others who want to + * {@link acquire} a section from the semaphore would be fall into the forever sleep. + * Therefore, never forget to calling the {@link release} function or utilize the + * {@link UniqueLock.try_lock} function instead with {@link Semaphore.get_lockable} to ensure + * the safety. + * + * @return Whether succeeded to acquire or not. + */ + public async try_acquire(): Promise { + // ALL OR NOTHING + if (this.acquiring_ < this.max_) { + ++this.acquiring_; + return true; + } else return false; + } - /** - * Tries to acquire a section until timeout. - * - * Attempts to acquire a section from the semaphore until timeout. If succeeded to acquire a - * section until the timeout, it returns `true`. Otherwise failed to acquiring a section in - * given the time, the function gives up the trial and returns `false`. - * - * Failed to acquiring a section in the given time (returns `false`), it means that there're - * someone who have already {@link acquire acquired} sections and do not return them over the - * time expiration. - * - * Note that, if you succeeded to acquire a section from the semaphore (returns `true) but do - * not call the {@link release} function after your business, the others who want to - * {@link acquire} a section from the semaphore would be fall into the forever sleep. - * Therefore, never forget to calling the {@link release} function or utilize the - * {@link UniqueLock.try_acquire_for} function instead with {@link Semaphore.get_lockable} to - * ensure the safety. - * - * @param ms The maximum miliseconds for waiting. - * @return Whether succeded to acquire or not. - */ - public async try_acquire_for(ms: number): Promise { - return new Promise((resolve) => { - if (this.acquiring_ < this.max_) { - ++this.acquiring_; - resolve(true); - } else { - // RESERVE ACQUIRE - const it: List.Iterator = this.queue_.insert( - this.queue_.end(), - { - handler: resolve, - lockType: LockType.KNOCK, - }, - ); + /** + * Tries to acquire a section until timeout. + * + * Attempts to acquire a section from the semaphore until timeout. If succeeded to acquire a + * section until the timeout, it returns `true`. Otherwise failed to acquiring a section in + * given the time, the function gives up the trial and returns `false`. + * + * Failed to acquiring a section in the given time (returns `false`), it means that there're + * someone who have already {@link acquire acquired} sections and do not return them over the + * time expiration. + * + * Note that, if you succeeded to acquire a section from the semaphore (returns `true) but do + * not call the {@link release} function after your business, the others who want to + * {@link acquire} a section from the semaphore would be fall into the forever sleep. + * Therefore, never forget to calling the {@link release} function or utilize the + * {@link UniqueLock.try_acquire_for} function instead with {@link Semaphore.get_lockable} to + * ensure the safety. + * + * @param ms The maximum miliseconds for waiting. + * @return Whether succeded to acquire or not. + */ + public async try_acquire_for(ms: number): Promise { + return new Promise((resolve) => { + if (this.acquiring_ < this.max_) { + ++this.acquiring_; + resolve(true); + } else { + // RESERVE ACQUIRE + const it: List.Iterator = this.queue_.insert( + this.queue_.end(), + { + handler: resolve, + lockType: LockType.KNOCK, + }, + ); - // AUTOMATIC RELEASE AFTER TIMEOUT - sleep_for(ms).then(() => { - // NOT YET, THEN DO RELEASE - if (it.value.handler !== null) this._Cancel(it); - }); - } + // AUTOMATIC RELEASE AFTER TIMEOUT + sleep_for(ms).then(() => { + // NOT YET, THEN DO RELEASE + if (it.value.handler !== null) this._Cancel(it); }); - } + } + }); + } - /** - * Tries to acquire a section until timeout. - * - * Attempts to acquire a section from the semaphore until time expiration. If succeeded to - * acquire a section until the time expiration, it returns `true`. Otherwise failed to - * acquiring a section in the given time, the function gives up the trial and returns `false`. - * - * Failed to acquiring a section in the given time (returns `false`), it means that there're - * someone who have already {@link acquire acquired} sections and do not return them over the - * time expiration. - * - * Note that, if you succeeded to acquire a section from the semaphore (returns `true) but do - * not call the {@link release} function after your business, the others who want to - * {@link acquire} a section from the semaphore would be fall into the forever sleep. - * Therefore, never forget to calling the {@link release} function or utilize the - * {@link UniqueLock.try_acquire_until} function instead with {@link Semaphore.get_lockable} - * to ensure the safety. - * - * @param at The maximum time point to wait. - * @return Whether succeded to acquire or not. - */ - public try_acquire_until(at: Date): Promise { - // COMPUTE MILLISECONDS TO WAIT - const now: Date = new Date(); - const ms: number = at.getTime() - now.getTime(); + /** + * Tries to acquire a section until timeout. + * + * Attempts to acquire a section from the semaphore until time expiration. If succeeded to + * acquire a section until the time expiration, it returns `true`. Otherwise failed to + * acquiring a section in the given time, the function gives up the trial and returns `false`. + * + * Failed to acquiring a section in the given time (returns `false`), it means that there're + * someone who have already {@link acquire acquired} sections and do not return them over the + * time expiration. + * + * Note that, if you succeeded to acquire a section from the semaphore (returns `true) but do + * not call the {@link release} function after your business, the others who want to + * {@link acquire} a section from the semaphore would be fall into the forever sleep. + * Therefore, never forget to calling the {@link release} function or utilize the + * {@link UniqueLock.try_acquire_until} function instead with {@link Semaphore.get_lockable} + * to ensure the safety. + * + * @param at The maximum time point to wait. + * @return Whether succeded to acquire or not. + */ + public try_acquire_until(at: Date): Promise { + // COMPUTE MILLISECONDS TO WAIT + const now: Date = new Date(); + const ms: number = at.getTime() - now.getTime(); - return this.try_acquire_for(ms); - } + return this.try_acquire_for(ms); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- RELEASES --------------------------------------------------------- */ - /** - * Release sections. - * - * When you call this {@link release} method and there're someone who are currently blocked - * by attemping to {@link acquire} a section from this semaphore, *n* of them - * (FIFO; first-in-first-out) would {@link acquire} those {@link release released} sections - * and continue their executions. - * - * Otherwise, there's not anyone who is {@link acquire acquiring} the section or number of - * the blocked are less than *n*, the {@link OutOfRange} error would be thrown. - * - * > As you know, when you succeeded to {@link acquire} a section, you don't have to forget - * > to calling this {@link release} method after your business. If you forget it, it would - * > be a terrible situation for the others who're attempting to {@link acquire} a section - * > from this semaphore. - * > - * > However, if you utilize the {@link UniqueLock} with {@link Semaphore.get_lockable}, you - * > don't need to consider about this {@link release} method. Just define your business into - * > a callback function as a parameter of methods of the {@link UniqueLock}, then this - * > {@link release} method would be automatically called by the {@link UniqueLock} after the - * > business. - * - * @param n Number of sections to be released. Default is 1. - * @throw {@link OutOfRange} when *n* is greater than currently {@link acquire acquired} sections. - */ - public async release(n: number = 1): Promise { - //---- - // VALIDATION - //---- - if (n < 1) - throw new InvalidArgument( - `Error on std.Semaphore.release(): parametric n is less than 1 -> (n = ${n}).`, - ); - else if (n > this.max_) - throw new OutOfRange( - `Error on std.Semaphore.release(): parametric n is greater than max -> (n = ${n}, max = ${this.max_}).`, - ); - else if (n > this.acquiring_) - throw new OutOfRange( - `Error on std.Semaphore.release(): parametric n is greater than acquiring -> (n = ${n}, acquiring = ${this.acquiring_}).`, - ); + /** + * Release sections. + * + * When you call this {@link release} method and there're someone who are currently blocked + * by attemping to {@link acquire} a section from this semaphore, *n* of them + * (FIFO; first-in-first-out) would {@link acquire} those {@link release released} sections + * and continue their executions. + * + * Otherwise, there's not anyone who is {@link acquire acquiring} the section or number of + * the blocked are less than *n*, the {@link OutOfRange} error would be thrown. + * + * > As you know, when you succeeded to {@link acquire} a section, you don't have to forget + * > to calling this {@link release} method after your business. If you forget it, it would + * > be a terrible situation for the others who're attempting to {@link acquire} a section + * > from this semaphore. + * > + * > However, if you utilize the {@link UniqueLock} with {@link Semaphore.get_lockable}, you + * > don't need to consider about this {@link release} method. Just define your business into + * > a callback function as a parameter of methods of the {@link UniqueLock}, then this + * > {@link release} method would be automatically called by the {@link UniqueLock} after the + * > business. + * + * @param n Number of sections to be released. Default is 1. + * @throw {@link OutOfRange} when *n* is greater than currently {@link acquire acquired} sections. + */ + public async release(n: number = 1): Promise { + //---- + // VALIDATION + //---- + if (n < 1) + throw new InvalidArgument( + `Error on std.Semaphore.release(): parametric n is less than 1 -> (n = ${n}).`, + ); + else if (n > this.max_) + throw new OutOfRange( + `Error on std.Semaphore.release(): parametric n is greater than max -> (n = ${n}, max = ${this.max_}).`, + ); + else if (n > this.acquiring_) + throw new OutOfRange( + `Error on std.Semaphore.release(): parametric n is greater than acquiring -> (n = ${n}, acquiring = ${this.acquiring_}).`, + ); - //---- - // RELEASE - //---- - const resolverList: IResolver[] = []; - while (this.queue_.empty() === false && resolverList.length < n) { - // COPY IF HANDLER EXISTS - const resolver: IResolver = this.queue_.front(); - if (resolver.handler !== null) resolverList.push({ ...resolver }); + //---- + // RELEASE + //---- + const resolverList: IResolver[] = []; + while (this.queue_.empty() === false && resolverList.length < n) { + // COPY IF HANDLER EXISTS + const resolver: IResolver = this.queue_.front(); + if (resolver.handler !== null) resolverList.push({ ...resolver }); - // DESTRUCT - this.queue_.pop_front(); - resolver.handler = null; - } + // DESTRUCT + this.queue_.pop_front(); + resolver.handler = null; + } - // COMPUTE REMAINED ACQUIRANCES - this.acquiring_ -= n - resolverList.length; + // COMPUTE REMAINED ACQUIRANCES + this.acquiring_ -= n - resolverList.length; - // CALL HANDLERS - for (const resolver of resolverList) - if (resolver.lockType === LockType.HOLD) resolver.handler!(); - else resolver.handler!(true); - } + // CALL HANDLERS + for (const resolver of resolverList) + if (resolver.lockType === LockType.HOLD) resolver.handler!(); + else resolver.handler!(true); + } - private _Cancel(it: List.Iterator): void { - // POP THE LISTENER - const handler: Function = it.value.handler!; + private _Cancel(it: List.Iterator): void { + // POP THE LISTENER + const handler: Function = it.value.handler!; - // DESTRUCTION - it.value.handler = null; - this.queue_.erase(it); + // DESTRUCTION + it.value.handler = null; + this.queue_.erase(it); - // RETURNS FAILURE - handler(false); - } + // RETURNS FAILURE + handler(false); + } } /** * */ export namespace Semaphore { - /** - * Capsules a {@link Semaphore} to be suitable for the {@link UniqueLock}. - * - * @param semaphore Target semaphore to capsule. - * @return Lockable instance suitable for the {@link UniqueLock} - */ - export function get_lockable< - SemaphoreT extends Pick< - Semaphore, - | "acquire" - | "try_acquire" - | "try_acquire_for" - | "try_acquire_until" - | "release" - >, - >(semaphore: SemaphoreT): ITimedLockable { - return new Lockable(semaphore); - } + /** + * Capsules a {@link Semaphore} to be suitable for the {@link UniqueLock}. + * + * @param semaphore Target semaphore to capsule. + * @return Lockable instance suitable for the {@link UniqueLock} + */ + export function get_lockable< + SemaphoreT extends Pick< + Semaphore, + | "acquire" + | "try_acquire" + | "try_acquire_for" + | "try_acquire_until" + | "release" + >, + >(semaphore: SemaphoreT): ITimedLockable { + return new Lockable(semaphore); + } - /** - * @internal - */ - export class Lockable< - SemaphoreT extends Pick< - Semaphore, - | "acquire" - | "try_acquire" - | "try_acquire_for" - | "try_acquire_until" - | "release" - >, - > implements ITimedLockable - { - private semahpore_: SemaphoreT; + /** + * @internal + */ + export class Lockable< + SemaphoreT extends Pick< + Semaphore, + | "acquire" + | "try_acquire" + | "try_acquire_for" + | "try_acquire_until" + | "release" + >, + > implements ITimedLockable + { + private semahpore_: SemaphoreT; - public constructor(semaphore: SemaphoreT) { - this.semahpore_ = semaphore; - } - public lock(): Promise { - return this.semahpore_.acquire(); - } - public unlock(): Promise { - return this.semahpore_.release(); - } + public constructor(semaphore: SemaphoreT) { + this.semahpore_ = semaphore; + } + public lock(): Promise { + return this.semahpore_.acquire(); + } + public unlock(): Promise { + return this.semahpore_.release(); + } - public try_lock(): Promise { - return this.semahpore_.try_acquire(); - } - public try_lock_for(ms: number): Promise { - return this.semahpore_.try_acquire_for(ms); - } - public try_lock_until(at: Date): Promise { - return this.semahpore_.try_acquire_until(at); - } + public try_lock(): Promise { + return this.semahpore_.try_acquire(); + } + public try_lock_for(ms: number): Promise { + return this.semahpore_.try_acquire_for(ms); + } + public try_lock_until(at: Date): Promise { + return this.semahpore_.try_acquire_until(at); } + } } interface IResolver { - handler: Function | null; - lockType: LockType; + handler: Function | null; + lockType: LockType; } diff --git a/src/thread/SharedLock.ts b/src/thread/SharedLock.ts index 2abbaa42..9980f08e 100644 --- a/src/thread/SharedLock.ts +++ b/src/thread/SharedLock.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -6,7 +7,6 @@ //================================================================ import { ISharedLockable } from "../base/thread/ISharedLockable"; import { ISharedTimedLockable } from "../base/thread/ISharedTimedLockable"; - import { SafeLock } from "../internal/thread/SafeLock"; /** @@ -25,161 +25,158 @@ export class SharedLock {} * @author Jeongho Nam - https://github.com/samchon */ export namespace SharedLock { - /** - * Read locks a shared mutex with your business. - * - * Shares a mutex until be the *closure* has been completed. If there're someone who have - * already {@link ILockable.lock monopolied} the mutex, the function call would be blocked - * until all of them to {@link unlock return} their acquisitions. - * - * When succeeded to {@link ISharedLockable.lock_shared share} the mutex, the {@link lock} - * function will call the *closure*, a custom function defning your business. After the - * *closure* function be returned, the {@link lock} function automatically - * {@link ISharedLockable.unlock_shared unlocks} the mutex, even if the *closure* function - * throws any error. - * - * Therefore, when using this {@link lock} function, you don't need to consider about - * {@link ISharedLockable.unlock_shared returning} the lock acquistion after your business. - * It would just be done automatically. - * - * @param mutex Target shared mutex to read lock. - * @param closure A function defining your business. - * - * @throw Exception would be thrown if the *closure* function throws any error. - */ - export function lock< - Mutex extends Pick, - >(mutex: Mutex, closure: Closure): Promise { - return SafeLock.lock( - () => mutex.lock_shared(), - () => mutex.unlock_shared(), - closure, - ); - } + /** + * Read locks a shared mutex with your business. + * + * Shares a mutex until be the *closure* has been completed. If there're someone who have + * already {@link ILockable.lock monopolied} the mutex, the function call would be blocked + * until all of them to {@link unlock return} their acquisitions. + * + * When succeeded to {@link ISharedLockable.lock_shared share} the mutex, the {@link lock} + * function will call the *closure*, a custom function defning your business. After the + * *closure* function be returned, the {@link lock} function automatically + * {@link ISharedLockable.unlock_shared unlocks} the mutex, even if the *closure* function + * throws any error. + * + * Therefore, when using this {@link lock} function, you don't need to consider about + * {@link ISharedLockable.unlock_shared returning} the lock acquistion after your business. + * It would just be done automatically. + * + * @param mutex Target shared mutex to read lock. + * @param closure A function defining your business. + * + * @throw Exception would be thrown if the *closure* function throws any error. + */ + export function lock< + Mutex extends Pick, + >(mutex: Mutex, closure: Closure): Promise { + return SafeLock.lock( + () => mutex.lock_shared(), + () => mutex.unlock_shared(), + closure, + ); + } - /** - * Tries to read lock a shared mutex with your business. - * - * Attemps to share a mutex without blocking. If succeeded to share the mutex immediately, it - * returns `true` directly. Otherwise there's someone who has already - * {@link ILockable.lock monopolied} the mutex, the function gives up the trial immediately - * and returns `false` directly without calling the *closure*. - * - * When succeeded to {@link ISharedLockable.lock_shared share} the mutex, the {@link try_lock} - * function will call the *closure*, a custom function defning your business. After the - * *closure* function be returned, the {@link try_lock} function automatically - * {@link ISharedLockable.unlock_shared unlocks} the mutex, even if the *closure* function - * throws any error. - * - * Therefore, when using this {@link try_lock} function, you don't need to consider about - * {@link ISharedLockable.unlock_shared returning} the lock acquistion after your business. - * It would just be done automatically. - * - * @param mutex Target shared mutex to try read lock. - * @param closure A function defining your business. - * @return Whether succeeded to share the mutex or not. - * - * @throw Exception would be thrown if the *closure* function throws any error. - */ - export function try_lock< - Mutex extends Pick< - ISharedLockable, - "try_lock_shared" | "unlock_shared" - >, - >(mutex: Mutex, closure: Closure): Promise { - return SafeLock.try_lock( - () => mutex.try_lock_shared(), - () => mutex.unlock_shared(), - closure, - ); - } + /** + * Tries to read lock a shared mutex with your business. + * + * Attemps to share a mutex without blocking. If succeeded to share the mutex immediately, it + * returns `true` directly. Otherwise there's someone who has already + * {@link ILockable.lock monopolied} the mutex, the function gives up the trial immediately + * and returns `false` directly without calling the *closure*. + * + * When succeeded to {@link ISharedLockable.lock_shared share} the mutex, the {@link try_lock} + * function will call the *closure*, a custom function defning your business. After the + * *closure* function be returned, the {@link try_lock} function automatically + * {@link ISharedLockable.unlock_shared unlocks} the mutex, even if the *closure* function + * throws any error. + * + * Therefore, when using this {@link try_lock} function, you don't need to consider about + * {@link ISharedLockable.unlock_shared returning} the lock acquistion after your business. + * It would just be done automatically. + * + * @param mutex Target shared mutex to try read lock. + * @param closure A function defining your business. + * @return Whether succeeded to share the mutex or not. + * + * @throw Exception would be thrown if the *closure* function throws any error. + */ + export function try_lock< + Mutex extends Pick, + >(mutex: Mutex, closure: Closure): Promise { + return SafeLock.try_lock( + () => mutex.try_lock_shared(), + () => mutex.unlock_shared(), + closure, + ); + } - /** - * Tries to read lock a shared mutex with your business until timeout. - * - * Attemps to share a mutex until timeout. If succeeded to share the mutex until timeout, it - * returns `true` after calling the *closure*. Otherwise failed to acquiring the shared lock - * in the given time, the function gives up the trial and returns `false` without calling the - * *closure*. - * - * Failed to acquring the shared lock in the given time (returns `false`), it means that - * there's someone who has already {@link ILockable.lock monopolied} the mutex and does not - * return it over the timeout. - * - * When succeeded to {@link ISharedLockable.lock_shared share} the mutex, the - * {@link try_lock_for} function will call the *closure*, a custom function defning your - * business. After the *closure* function be returned, the {@link try_lock} function - * automatically {@link ISharedLockable.unlock_shared unlocks} the mutex, even if the - * *closure* function throws any error. - * - * Therefore, when using this {@link try_lock_for} function, you don't need to consider about - * {@link ISharedLockable.unlock_shared returning} the lock acquistion after your business. - * It would just be done automatically. - * - * @param mutex Target mutex to try lock until timeout. - * @param ms The maximum miliseconds for waiting. - * @param closure A function defining your business. - * @return Whether succeeded to share the mutex or not. - * - * @throw Exception would be thrown if the *closure* function throws any error. - */ - export function try_lock_for< - Mutex extends Pick< - ISharedTimedLockable, - "try_lock_shared_for" | "unlock_shared" - >, - >(mutex: Mutex, ms: number, closure: Closure): Promise { - return SafeLock.try_lock( - () => mutex.try_lock_shared_for(ms), - () => mutex.unlock_shared(), - closure, - ); - } + /** + * Tries to read lock a shared mutex with your business until timeout. + * + * Attemps to share a mutex until timeout. If succeeded to share the mutex until timeout, it + * returns `true` after calling the *closure*. Otherwise failed to acquiring the shared lock + * in the given time, the function gives up the trial and returns `false` without calling the + * *closure*. + * + * Failed to acquring the shared lock in the given time (returns `false`), it means that + * there's someone who has already {@link ILockable.lock monopolied} the mutex and does not + * return it over the timeout. + * + * When succeeded to {@link ISharedLockable.lock_shared share} the mutex, the + * {@link try_lock_for} function will call the *closure*, a custom function defning your + * business. After the *closure* function be returned, the {@link try_lock} function + * automatically {@link ISharedLockable.unlock_shared unlocks} the mutex, even if the + * *closure* function throws any error. + * + * Therefore, when using this {@link try_lock_for} function, you don't need to consider about + * {@link ISharedLockable.unlock_shared returning} the lock acquistion after your business. + * It would just be done automatically. + * + * @param mutex Target mutex to try lock until timeout. + * @param ms The maximum miliseconds for waiting. + * @param closure A function defining your business. + * @return Whether succeeded to share the mutex or not. + * + * @throw Exception would be thrown if the *closure* function throws any error. + */ + export function try_lock_for< + Mutex extends Pick< + ISharedTimedLockable, + "try_lock_shared_for" | "unlock_shared" + >, + >(mutex: Mutex, ms: number, closure: Closure): Promise { + return SafeLock.try_lock( + () => mutex.try_lock_shared_for(ms), + () => mutex.unlock_shared(), + closure, + ); + } - /** - * Tries to read lock a shared mutex with your business until time expiration. - * - * Attemps to share a mutex until time expiration. If succeeded to share the mutex until the - * time expiration, it returns `true` after calling the *closure*. Otherwise failed to - * acquiring the shared lock in the given time, the function gives up the trial and returns - * `false` without calling the *closure*. - * - * Failed to acquring the shared lock in the given time (returns `false`), it means that - * there's someone who has already {@link ILockable.lock monopolied} the mutex and does not - * return it over the time expiration. - * - * When succeeded to {@link ISharedLockable.lock_shared share} the mutex, the - * {@link try_lock_until} function will call the *closure*, a custom function defning your - * business. After the *closure* function be returned, the {@link try_lock} function - * automatically {@link ISharedLockable.unlock_shared unlocks} the mutex, even if the - * *closure* function throws any error. - * - * Therefore, when using this {@link try_lock_until} function, you don't need to consider - * about {@link ISharedLockable.unlock_shared returning} the lock acquistion after your - * business. It would just be done automatically. - * - * @param mutex Target mutex to try lock until time expiration. - * @param at The maximum time point to wait. - * @param closure A function defining your business. - * @return Whether succeeded to share the mutex or not. - * - * @throw Exception would be thrown if the *closure* function throws any error. - */ - export function try_lock_until< - Mutex extends Pick< - ISharedTimedLockable, - "try_lock_shared_until" | "unlock_shared" - >, - >(mutex: Mutex, at: Date, closure: Closure): Promise { - return SafeLock.try_lock( - () => mutex.try_lock_shared_until(at), - () => mutex.unlock_shared(), - closure, - ); - } + /** + * Tries to read lock a shared mutex with your business until time expiration. + * + * Attemps to share a mutex until time expiration. If succeeded to share the mutex until the + * time expiration, it returns `true` after calling the *closure*. Otherwise failed to + * acquiring the shared lock in the given time, the function gives up the trial and returns + * `false` without calling the *closure*. + * + * Failed to acquring the shared lock in the given time (returns `false`), it means that + * there's someone who has already {@link ILockable.lock monopolied} the mutex and does not + * return it over the time expiration. + * + * When succeeded to {@link ISharedLockable.lock_shared share} the mutex, the + * {@link try_lock_until} function will call the *closure*, a custom function defning your + * business. After the *closure* function be returned, the {@link try_lock} function + * automatically {@link ISharedLockable.unlock_shared unlocks} the mutex, even if the + * *closure* function throws any error. + * + * Therefore, when using this {@link try_lock_until} function, you don't need to consider + * about {@link ISharedLockable.unlock_shared returning} the lock acquistion after your + * business. It would just be done automatically. + * + * @param mutex Target mutex to try lock until time expiration. + * @param at The maximum time point to wait. + * @param closure A function defining your business. + * @return Whether succeeded to share the mutex or not. + * + * @throw Exception would be thrown if the *closure* function throws any error. + */ + export function try_lock_until< + Mutex extends Pick< + ISharedTimedLockable, + "try_lock_shared_until" | "unlock_shared" + >, + >(mutex: Mutex, at: Date, closure: Closure): Promise { + return SafeLock.try_lock( + () => mutex.try_lock_shared_until(at), + () => mutex.unlock_shared(), + closure, + ); + } - /** - * Type of closure function defining your business logic. - */ - type Closure = () => void | Promise; + /** + * Type of closure function defining your business logic. + */ + type Closure = () => void | Promise; } diff --git a/src/thread/SharedMutex.ts b/src/thread/SharedMutex.ts index 7ed1c211..9771d8d3 100644 --- a/src/thread/SharedMutex.ts +++ b/src/thread/SharedMutex.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -13,63 +14,63 @@ import { SharedTimedMutex } from "./SharedTimedMutex"; * @author Jeongho Nam - https://github.com/samchon */ export class SharedMutex implements ISharedLockable { - private mutex_: SharedTimedMutex; + private mutex_: SharedTimedMutex; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor() { - this.mutex_ = new SharedTimedMutex(this); - } + /** + * Default Constructor. + */ + public constructor() { + this.mutex_ = new SharedTimedMutex(this); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- WRITE LOCK --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public lock(): Promise { - return this.mutex_.lock(); - } + /** + * @inheritDoc + */ + public lock(): Promise { + return this.mutex_.lock(); + } - /** - * @inheritDoc - */ - public try_lock(): Promise { - return this.mutex_.try_lock(); - } + /** + * @inheritDoc + */ + public try_lock(): Promise { + return this.mutex_.try_lock(); + } - /** - * @inheritDoc - */ - public unlock(): Promise { - return this.mutex_.unlock(); - } + /** + * @inheritDoc + */ + public unlock(): Promise { + return this.mutex_.unlock(); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- READ LOCK --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public lock_shared(): Promise { - return this.mutex_.lock_shared(); - } + /** + * @inheritDoc + */ + public lock_shared(): Promise { + return this.mutex_.lock_shared(); + } - /** - * @inheritDoc - */ - public try_lock_shared(): Promise { - return this.mutex_.try_lock_shared(); - } + /** + * @inheritDoc + */ + public try_lock_shared(): Promise { + return this.mutex_.try_lock_shared(); + } - /** - * @inheritDoc - */ - public unlock_shared(): Promise { - return this.mutex_.unlock_shared(); - } + /** + * @inheritDoc + */ + public unlock_shared(): Promise { + return this.mutex_.unlock_shared(); + } } diff --git a/src/thread/SharedTimedMutex.ts b/src/thread/SharedTimedMutex.ts index c7e245be..2022a34c 100644 --- a/src/thread/SharedTimedMutex.ts +++ b/src/thread/SharedTimedMutex.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -6,12 +7,10 @@ //================================================================ import { ILockable } from "../base/thread/ILockable"; import { ISharedTimedLockable } from "../base/thread/ISharedTimedLockable"; - -import { AccessType } from "../internal/thread/AccessType"; -import { LockType } from "../internal/thread/LockType"; - import { List } from "../container/List"; import { InvalidArgument } from "../exception/InvalidArgument"; +import { AccessType } from "../internal/thread/AccessType"; +import { LockType } from "../internal/thread/LockType"; import { sleep_for } from "./global"; /** @@ -20,287 +19,279 @@ import { sleep_for } from "./global"; * @author Jeongho Nam - https://github.com/samchon */ export class SharedTimedMutex implements ISharedTimedLockable { - private source_: ILockable; - private queue_: List; + private source_: ILockable; + private queue_: List; - private writing_: number; - private reading_: number; + private writing_: number; + private reading_: number; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor(); - - /** - * @internal - */ - public constructor(source: ILockable); - - public constructor(source: ILockable | null = null) { - this.source_ = source !== null ? source : this; - this.queue_ = new List(); - - this.writing_ = 0; - this.reading_ = 0; - } + /** + * Default Constructor. + */ + public constructor(); - private _Current_access_type(): AccessType | null { - return this.queue_.empty() ? null : this.queue_.front().accessType; - } + /** + * @internal + */ + public constructor(source: ILockable); - /* --------------------------------------------------------- - WRITE LOCK - --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public lock(): Promise { - return new Promise((resolve) => { - // CONSTRUCT RESOLVER - const resolver: IResolver = { - handler: - this.writing_++ === 0 && this.reading_ === 0 - ? null - : resolve, - accessType: AccessType.WRITE, - lockType: LockType.HOLD, - }; - this.queue_.push_back(resolver); - - // LOCK OR WAIT - if (resolver.handler === null) resolve(); - }); - } + public constructor(source: ILockable | null = null) { + this.source_ = source !== null ? source : this; + this.queue_ = new List(); - /** - * @inheritDoc - */ - public async try_lock(): Promise { - // LOCKABLE ? - if (this.writing_ !== 0 || this.reading_ !== 0) return false; - - // CONSTRUCT RESOLVER - this.queue_.push_back({ - handler: null, - accessType: AccessType.WRITE, - lockType: LockType.KNOCK, - }); + this.writing_ = 0; + this.reading_ = 0; + } - // RETURNS - ++this.writing_; - return true; - } + private _Current_access_type(): AccessType | null { + return this.queue_.empty() ? null : this.queue_.front().accessType; + } - /** - * @inheritDoc - */ - public try_lock_for(ms: number): Promise { - return new Promise((resolve) => { - // CONSTRUCT RESOLVER - const it: List.Iterator = this.queue_.insert( - this.queue_.end(), - { - handler: - this.writing_++ === 0 && this.reading_ === 0 - ? null - : resolve, - accessType: AccessType.WRITE, - lockType: LockType.KNOCK, - }, - ); - - if (it.value.handler === null) resolve(true); // SUCCESS - else { - // AUTOMATIC UNLOCK AFTER TIMEOUT - sleep_for(ms).then(() => { - // NOT YET, THEN DO UNLOCK - if (it.value.handler !== null) { - --this.writing_; - this._Cancel(it); - } - }); - } + /* --------------------------------------------------------- + WRITE LOCK + --------------------------------------------------------- */ + /** + * @inheritDoc + */ + public lock(): Promise { + return new Promise((resolve) => { + // CONSTRUCT RESOLVER + const resolver: IResolver = { + handler: this.writing_++ === 0 && this.reading_ === 0 ? null : resolve, + accessType: AccessType.WRITE, + lockType: LockType.HOLD, + }; + this.queue_.push_back(resolver); + + // LOCK OR WAIT + if (resolver.handler === null) resolve(); + }); + } + + /** + * @inheritDoc + */ + public async try_lock(): Promise { + // LOCKABLE ? + if (this.writing_ !== 0 || this.reading_ !== 0) return false; + + // CONSTRUCT RESOLVER + this.queue_.push_back({ + handler: null, + accessType: AccessType.WRITE, + lockType: LockType.KNOCK, + }); + + // RETURNS + ++this.writing_; + return true; + } + + /** + * @inheritDoc + */ + public try_lock_for(ms: number): Promise { + return new Promise((resolve) => { + // CONSTRUCT RESOLVER + const it: List.Iterator = this.queue_.insert( + this.queue_.end(), + { + handler: + this.writing_++ === 0 && this.reading_ === 0 ? null : resolve, + accessType: AccessType.WRITE, + lockType: LockType.KNOCK, + }, + ); + + if (it.value.handler === null) resolve(true); // SUCCESS + else { + // AUTOMATIC UNLOCK AFTER TIMEOUT + sleep_for(ms).then(() => { + // NOT YET, THEN DO UNLOCK + if (it.value.handler !== null) { + --this.writing_; + this._Cancel(it); + } }); - } - - /** - * @inheritDoc - */ - public async try_lock_until(at: Date): Promise { - // COMPUTE MILLISECONDS TO WAIT - const now: Date = new Date(); - const ms: number = at.getTime() - now.getTime(); - - return await this.try_lock_for(ms); - } - - /** - * @inheritDoc - */ - public async unlock(): Promise { - if (this._Current_access_type() !== AccessType.WRITE) - throw new InvalidArgument( - `Error on std.${this.source_.constructor.name}.unlock(): this mutex is free on the unique lock.`, - ); - - --this.writing_; - this.queue_.pop_front(); - - this._Release(); - } - - /* --------------------------------------------------------- + } + }); + } + + /** + * @inheritDoc + */ + public async try_lock_until(at: Date): Promise { + // COMPUTE MILLISECONDS TO WAIT + const now: Date = new Date(); + const ms: number = at.getTime() - now.getTime(); + + return await this.try_lock_for(ms); + } + + /** + * @inheritDoc + */ + public async unlock(): Promise { + if (this._Current_access_type() !== AccessType.WRITE) + throw new InvalidArgument( + `Error on std.${this.source_.constructor.name}.unlock(): this mutex is free on the unique lock.`, + ); + + --this.writing_; + this.queue_.pop_front(); + + this._Release(); + } + + /* --------------------------------------------------------- READ LOCK --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public lock_shared(): Promise { - return new Promise((resolve) => { - const resolver: IResolver = { - handler: this.writing_ === 0 ? null : resolve, - accessType: AccessType.READ, - lockType: LockType.HOLD, - }; - this.queue_.push_back(resolver); - - ++this.reading_; - if (resolver.handler === null) resolve(); - }); - } - - /** - * @inheritDoc - */ - public async try_lock_shared(): Promise { - if (this.writing_ !== 0) return false; - - ++this.reading_; - this.queue_.push_back({ - handler: null, - accessType: AccessType.READ, - lockType: LockType.KNOCK, - }); - return true; - } - - /** - * @inheritDoc - */ - public try_lock_shared_for(ms: number): Promise { - return new Promise((resolve) => { - // CONSTRUCT RESOLVER - const it: List.Iterator = this.queue_.insert( - this.queue_.end(), - { - handler: this.writing_ === 0 ? null : resolve, - accessType: AccessType.READ, - lockType: LockType.KNOCK, - }, - ); - - ++this.reading_; - if (it.value.handler === null) resolve(true); - else { - // AUTOMATIC UNLOCK AFTER TIMEOUT - sleep_for(ms).then(() => { - // NOT YET, THEN DO UNLOCK - if (it.value.handler !== null) { - --this.reading_; - this._Cancel(it); - } - }); - } + /** + * @inheritDoc + */ + public lock_shared(): Promise { + return new Promise((resolve) => { + const resolver: IResolver = { + handler: this.writing_ === 0 ? null : resolve, + accessType: AccessType.READ, + lockType: LockType.HOLD, + }; + this.queue_.push_back(resolver); + + ++this.reading_; + if (resolver.handler === null) resolve(); + }); + } + + /** + * @inheritDoc + */ + public async try_lock_shared(): Promise { + if (this.writing_ !== 0) return false; + + ++this.reading_; + this.queue_.push_back({ + handler: null, + accessType: AccessType.READ, + lockType: LockType.KNOCK, + }); + return true; + } + + /** + * @inheritDoc + */ + public try_lock_shared_for(ms: number): Promise { + return new Promise((resolve) => { + // CONSTRUCT RESOLVER + const it: List.Iterator = this.queue_.insert( + this.queue_.end(), + { + handler: this.writing_ === 0 ? null : resolve, + accessType: AccessType.READ, + lockType: LockType.KNOCK, + }, + ); + + ++this.reading_; + if (it.value.handler === null) resolve(true); + else { + // AUTOMATIC UNLOCK AFTER TIMEOUT + sleep_for(ms).then(() => { + // NOT YET, THEN DO UNLOCK + if (it.value.handler !== null) { + --this.reading_; + this._Cancel(it); + } }); - } - - /** - * @inheritDoc - */ - public async try_lock_shared_until(at: Date): Promise { - // COMPUTE MILLISECONDS TO WAIT - const now: Date = new Date(); - const ms: number = at.getTime() - now.getTime(); - - return await this.try_lock_shared_for(ms); - } - - /** - * @inheritDoc - */ - public async unlock_shared(): Promise { - if (this._Current_access_type() !== AccessType.READ) - throw new InvalidArgument( - `Error on std.${this.source_.constructor.name}.unlock_shared(): this mutex is free on the shared lock.`, - ); - - --this.reading_; - this.queue_.pop_front(); - - this._Release(); - } - - /* --------------------------------------------------------- + } + }); + } + + /** + * @inheritDoc + */ + public async try_lock_shared_until(at: Date): Promise { + // COMPUTE MILLISECONDS TO WAIT + const now: Date = new Date(); + const ms: number = at.getTime() - now.getTime(); + + return await this.try_lock_shared_for(ms); + } + + /** + * @inheritDoc + */ + public async unlock_shared(): Promise { + if (this._Current_access_type() !== AccessType.READ) + throw new InvalidArgument( + `Error on std.${this.source_.constructor.name}.unlock_shared(): this mutex is free on the shared lock.`, + ); + + --this.reading_; + this.queue_.pop_front(); + + this._Release(); + } + + /* --------------------------------------------------------- RELEASE --------------------------------------------------------- */ - private _Release(): void { - // STEP TO THE NEXT LOCKS - const current: AccessType = this._Current_access_type()!; - const resolverList: IResolver[] = []; - - for (const resolver of this.queue_) { - // DIFFERENT ACCESS TYPE COMES? - if (resolver.accessType !== current) break; - // COPY AND CLEAR - else if (resolver.handler !== null) { - resolverList.push({ ...resolver }); - resolver.handler = null; - } - - // STOP AFTER WRITE LOCK - if (resolver.accessType === AccessType.WRITE) break; - } - - // CALL THE HANDLERS - for (const resolver of resolverList) - if (resolver.lockType === LockType.HOLD) resolver.handler!(); - else resolver.handler!(true); + private _Release(): void { + // STEP TO THE NEXT LOCKS + const current: AccessType = this._Current_access_type()!; + const resolverList: IResolver[] = []; + + for (const resolver of this.queue_) { + // DIFFERENT ACCESS TYPE COMES? + if (resolver.accessType !== current) break; + // COPY AND CLEAR + else if (resolver.handler !== null) { + resolverList.push({ ...resolver }); + resolver.handler = null; + } + + // STOP AFTER WRITE LOCK + if (resolver.accessType === AccessType.WRITE) break; } - private _Cancel(it: List.Iterator): void { - //---- - // POP THE RELEASE - //---- - // DO RASE - this.queue_.erase(it); - - // EXTRACT HANDLER TO AVOID THE `this._Release()` - const handler: Function = it.value.handler!; - it.value.handler = null; - - //---- - // POST-PROCESS - //---- - // CHECK THE PREVIOUS RESOLVER - const prev: List.Iterator = it.prev(); - - // RELEASE IF IT IS THE LASTEST RESOLVER - if ( - prev.equals(this.queue_.end()) === false && - prev.value.handler === null - ) - this._Release(); - - // (LAZY) RETURNS FAILURE - handler(false); - } + // CALL THE HANDLERS + for (const resolver of resolverList) + if (resolver.lockType === LockType.HOLD) resolver.handler!(); + else resolver.handler!(true); + } + + private _Cancel(it: List.Iterator): void { + //---- + // POP THE RELEASE + //---- + // DO RASE + this.queue_.erase(it); + + // EXTRACT HANDLER TO AVOID THE `this._Release()` + const handler: Function = it.value.handler!; + it.value.handler = null; + + //---- + // POST-PROCESS + //---- + // CHECK THE PREVIOUS RESOLVER + const prev: List.Iterator = it.prev(); + + // RELEASE IF IT IS THE LASTEST RESOLVER + if (prev.equals(this.queue_.end()) === false && prev.value.handler === null) + this._Release(); + + // (LAZY) RETURNS FAILURE + handler(false); + } } interface IResolver { - handler: Function | null; - accessType: AccessType; // read or write - lockType: LockType; // void or boolean + handler: Function | null; + accessType: AccessType; // read or write + lockType: LockType; // void or boolean } diff --git a/src/thread/Singleton.ts b/src/thread/Singleton.ts index 833e2323..4e8decbe 100644 --- a/src/thread/Singleton.ts +++ b/src/thread/Singleton.ts @@ -4,19 +4,18 @@ * @author Jeongho Nam - https://github.com/samchon */ export class Singleton { - private readonly closure_: (...args: Args) => T; - private value_: T | object; + private readonly closure_: (...args: Args) => T; + private value_: T | object; - public constructor(closure: (...args: Args) => T) { - this.closure_ = closure; - this.value_ = NOT_MOUNTED_YET; - } + public constructor(closure: (...args: Args) => T) { + this.closure_ = closure; + this.value_ = NOT_MOUNTED_YET; + } - public get(...args: Args): T { - if (this.value_ === NOT_MOUNTED_YET) - this.value_ = this.closure_(...args); - return this.value_ as T; - } + public get(...args: Args): T { + if (this.value_ === NOT_MOUNTED_YET) this.value_ = this.closure_(...args); + return this.value_ as T; + } } const NOT_MOUNTED_YET = {}; diff --git a/src/thread/TimedMutex.ts b/src/thread/TimedMutex.ts index ccb668cf..ccd9dcd3 100644 --- a/src/thread/TimedMutex.ts +++ b/src/thread/TimedMutex.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -13,56 +14,56 @@ import { SharedTimedMutex } from "./SharedTimedMutex"; * @author Jeongho Nam - https://github.com/samchon */ export class TimedMutex implements ITimedLockable { - private mutex_: SharedTimedMutex; + private mutex_: SharedTimedMutex; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ - /** - * Default Constructor. - */ - public constructor() { - this.mutex_ = new SharedTimedMutex(this); - } + /** + * Default Constructor. + */ + public constructor() { + this.mutex_ = new SharedTimedMutex(this); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- LOCK & UNLOCK --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public lock(): Promise { - return this.mutex_.lock(); - } + /** + * @inheritDoc + */ + public lock(): Promise { + return this.mutex_.lock(); + } - /** - * @inheritDoc - */ - public try_lock(): Promise { - return this.mutex_.try_lock(); - } + /** + * @inheritDoc + */ + public try_lock(): Promise { + return this.mutex_.try_lock(); + } - /** - * @inheritDoc - */ - public unlock(): Promise { - return this.mutex_.unlock(); - } + /** + * @inheritDoc + */ + public unlock(): Promise { + return this.mutex_.unlock(); + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- TIMED LOCK --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public try_lock_for(ms: number): Promise { - return this.mutex_.try_lock_for(ms); - } + /** + * @inheritDoc + */ + public try_lock_for(ms: number): Promise { + return this.mutex_.try_lock_for(ms); + } - /** - * @inheritDoc - */ - public try_lock_until(at: Date): Promise { - return this.mutex_.try_lock_until(at); - } + /** + * @inheritDoc + */ + public try_lock_until(at: Date): Promise { + return this.mutex_.try_lock_until(at); + } } diff --git a/src/thread/TimedSingleton.ts b/src/thread/TimedSingleton.ts index 44440c8d..ba5291f1 100644 --- a/src/thread/TimedSingleton.ts +++ b/src/thread/TimedSingleton.ts @@ -8,34 +8,34 @@ * @author Jeongho Nam - https://github.com/samchon */ export class TimedSingleton { - private readonly interval_: number; - private readonly closure_: (...args: Args) => T; - private expired_at_: number; - private value_: T; + private readonly interval_: number; + private readonly closure_: (...args: Args) => T; + private expired_at_: number; + private value_: T; - /** - * Initializer Constructor. - * - * @param interval Specific interval time, to determine whether re-generation of the singleton value is required or not, as milliseconds - * @param closure Lazy constructor function returning the target value - */ - public constructor(interval: number, closure: (...args: Args) => T) { - this.interval_ = interval; - this.closure_ = closure; - this.value_ = null!; - this.expired_at_ = 0; - } + /** + * Initializer Constructor. + * + * @param interval Specific interval time, to determine whether re-generation of the singleton value is required or not, as milliseconds + * @param closure Lazy constructor function returning the target value + */ + public constructor(interval: number, closure: (...args: Args) => T) { + this.interval_ = interval; + this.closure_ = closure; + this.value_ = null!; + this.expired_at_ = 0; + } - /** - * Get value. - * - * @returns The lazy constructed value - */ - public get(...args: Args): T { - if (Date.now() >= this.expired_at_) { - this.expired_at_ = Date.now() + this.interval_; - this.value_ = this.closure_(...args); - } - return this.value_; + /** + * Get value. + * + * @returns The lazy constructed value + */ + public get(...args: Args): T { + if (Date.now() >= this.expired_at_) { + this.expired_at_ = Date.now() + this.interval_; + this.value_ = this.closure_(...args); } + return this.value_; + } } diff --git a/src/thread/UniqueLock.ts b/src/thread/UniqueLock.ts index a1bff033..d47d45a4 100644 --- a/src/thread/UniqueLock.ts +++ b/src/thread/UniqueLock.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -6,7 +7,6 @@ //================================================================ import { ILockable } from "../base/thread/ILockable"; import { ITimedLockable } from "../base/thread/ITimedLockable"; - import { SafeLock } from "../internal/thread/SafeLock"; /** @@ -25,154 +25,154 @@ export class UniqueLock {} * @author Jeongho Nam - https://github.com/samchon */ export namespace UniqueLock { - /** - * Write locks a mutex with your business logic code. - * - * Monopolies a mutex until be the *closure* has been completed. If there're someone who have - * already {@link ILockable.lock monopolied} or {@link ISharedLockable.lock shared} the mutex, - * the function call would be blocked until all of them return their acquisitions by calling - * {@link ILockable.unlock} or {@link ISharedLockable.unlock_shared} methods. - * - * When succeeded to {@link ILockable.lock monopoly} the mutex, the {@link lock} function will - * call the *closure*, a custom function definig your business. After the *closure* function - * be returned, the {@link lock} function automatically {@link ILockable.unlock unlocks} the - * mutex, even if the *closure* function throws any error. - * - * Therefore, when using this {@link lock} function, you don't need to consider about - * {@link ILockable.unlock returning} the lock acquistion after your business. It would just - * be done automatically. - * - * @param mutex Target mutex to write lock. - * @param closure A function defining your business. - * - * @throw Exception would be thrown if the *closure* function throws any error. - */ - export function lock>( - mutex: Mutex, - closure: Closure, - ): Promise { - return SafeLock.lock( - () => mutex.lock(), - () => mutex.unlock(), - closure, - ); - } + /** + * Write locks a mutex with your business logic code. + * + * Monopolies a mutex until be the *closure* has been completed. If there're someone who have + * already {@link ILockable.lock monopolied} or {@link ISharedLockable.lock shared} the mutex, + * the function call would be blocked until all of them return their acquisitions by calling + * {@link ILockable.unlock} or {@link ISharedLockable.unlock_shared} methods. + * + * When succeeded to {@link ILockable.lock monopoly} the mutex, the {@link lock} function will + * call the *closure*, a custom function definig your business. After the *closure* function + * be returned, the {@link lock} function automatically {@link ILockable.unlock unlocks} the + * mutex, even if the *closure* function throws any error. + * + * Therefore, when using this {@link lock} function, you don't need to consider about + * {@link ILockable.unlock returning} the lock acquistion after your business. It would just + * be done automatically. + * + * @param mutex Target mutex to write lock. + * @param closure A function defining your business. + * + * @throw Exception would be thrown if the *closure* function throws any error. + */ + export function lock>( + mutex: Mutex, + closure: Closure, + ): Promise { + return SafeLock.lock( + () => mutex.lock(), + () => mutex.unlock(), + closure, + ); + } - /** - * Tries to write lock a mutex with your business. - * - * Attempts to monopoly a mutex without blocking. If succeeded to monopoly the mutex - * immediately, it returns `true` after calling the *closure*. Otherwise there's someone who - * has already {@link ILockable.lock monopolied} or {@link ISharedLockable.lock shared} the - * mutex, the function gives up the trial immediately and returns `false` directly without - * calling the *closure*. - * - * When succeeded to {@link ILockable.lock monopoly} the mutex, the {@link try_lock} function - * will call the *closure*, a custom function definig your business. After the *closure* - * function be returned, the {@link try_lock} function automatically - * {@link ILockable.unlock unlocks} the mutex, even if the *closure* function throws any - * error. - * - * Therefore, when using this {@link try_lock} function, you don't need to consider about - * {@link ILockable.unlock returning} the lock acquistion after your business. It would just - * be done automatically. - * - * @param mutex Target mutex to try write lock. - * @param closure A function defining your business. - * @return Whether succeeded to monopoly the mutex or not. - * - * @throw Exception would be thrown if the *closure* function throws any error. - */ - export function try_lock< - Mutex extends Pick, - >(mutex: Mutex, closure: Closure): Promise { - return SafeLock.try_lock( - () => mutex.try_lock(), - () => mutex.unlock(), - closure, - ); - } + /** + * Tries to write lock a mutex with your business. + * + * Attempts to monopoly a mutex without blocking. If succeeded to monopoly the mutex + * immediately, it returns `true` after calling the *closure*. Otherwise there's someone who + * has already {@link ILockable.lock monopolied} or {@link ISharedLockable.lock shared} the + * mutex, the function gives up the trial immediately and returns `false` directly without + * calling the *closure*. + * + * When succeeded to {@link ILockable.lock monopoly} the mutex, the {@link try_lock} function + * will call the *closure*, a custom function definig your business. After the *closure* + * function be returned, the {@link try_lock} function automatically + * {@link ILockable.unlock unlocks} the mutex, even if the *closure* function throws any + * error. + * + * Therefore, when using this {@link try_lock} function, you don't need to consider about + * {@link ILockable.unlock returning} the lock acquistion after your business. It would just + * be done automatically. + * + * @param mutex Target mutex to try write lock. + * @param closure A function defining your business. + * @return Whether succeeded to monopoly the mutex or not. + * + * @throw Exception would be thrown if the *closure* function throws any error. + */ + export function try_lock< + Mutex extends Pick, + >(mutex: Mutex, closure: Closure): Promise { + return SafeLock.try_lock( + () => mutex.try_lock(), + () => mutex.unlock(), + closure, + ); + } - /** - * Tries to write lock a mutex with your business until timeout. - * - * Attempts to monopoly a mutex until timeout. If succeeded to monopoly the mutex until the - * timeout, it returns `true` after calling the *closure*. Otherwise failed to acquiring the - * lock in the given time, the function gives up the trial and returns `false` without calling - * the *closure*. - * - * Failed to acquiring the lock in the given time (returns `false`), it means that there's - * someone who has already {@link ILockable.lock monopolied} or {@link ISharedLockable.lock} - * the mutex and does not return it over the timeout. - * - * When succeeded to {@link ILockable.lock monopoly} the mutex, the {@link try_lock_for} - * function will call the *closure*, a custom function definig your business. After the - * *closure* function be returned, the {@link try_lock_for} function automatically - * {@link ILockable.unlock unlocks} the mutex and returns `true`, even if the *closure* - * function throws any error. - * - * Therefore, when using this {@link try_lock_for} function, you don't need to consider about - * {@link ILockable.unlock returning} the lock acquistion after your business. It would just - * be done automatically. - * - * @param mutex Target mutex to try write lock until timeout. - * @param ms The maximum miliseconds for waiting. - * @param closure A function defining your business. - * @return Whether succeeded to monopoly the mutex or not. - * - * @throw Exception would be thrown if the *closure* function throws any error. - */ - export function try_lock_for< - Mutex extends Pick, - >(mutex: Mutex, ms: number, closure: Closure): Promise { - return SafeLock.try_lock( - () => mutex.try_lock_for(ms), - () => mutex.unlock(), - closure, - ); - } + /** + * Tries to write lock a mutex with your business until timeout. + * + * Attempts to monopoly a mutex until timeout. If succeeded to monopoly the mutex until the + * timeout, it returns `true` after calling the *closure*. Otherwise failed to acquiring the + * lock in the given time, the function gives up the trial and returns `false` without calling + * the *closure*. + * + * Failed to acquiring the lock in the given time (returns `false`), it means that there's + * someone who has already {@link ILockable.lock monopolied} or {@link ISharedLockable.lock} + * the mutex and does not return it over the timeout. + * + * When succeeded to {@link ILockable.lock monopoly} the mutex, the {@link try_lock_for} + * function will call the *closure*, a custom function definig your business. After the + * *closure* function be returned, the {@link try_lock_for} function automatically + * {@link ILockable.unlock unlocks} the mutex and returns `true`, even if the *closure* + * function throws any error. + * + * Therefore, when using this {@link try_lock_for} function, you don't need to consider about + * {@link ILockable.unlock returning} the lock acquistion after your business. It would just + * be done automatically. + * + * @param mutex Target mutex to try write lock until timeout. + * @param ms The maximum miliseconds for waiting. + * @param closure A function defining your business. + * @return Whether succeeded to monopoly the mutex or not. + * + * @throw Exception would be thrown if the *closure* function throws any error. + */ + export function try_lock_for< + Mutex extends Pick, + >(mutex: Mutex, ms: number, closure: Closure): Promise { + return SafeLock.try_lock( + () => mutex.try_lock_for(ms), + () => mutex.unlock(), + closure, + ); + } - /** - * Tries to write lock a mutex with your business until time expiration. - * - * Attempts to monopoly a mutex until time expiration. If succeeded to monopoly the mutex - * until the time expiration, it returns `true` after calling the *closure*. Otherwise failed - * to acquiring the lock in the given time, the function gives up the trial and returns - * `false` without calling the *closure*. - * - * Failed to acquiring the lock in the given time (returns `false`), it means that there's - * someone who has already {@link ILockable.lock monopolied} or {@link ISharedLockable.lock} - * the mutex and does not return it over the time expiration. - * - * When succeeded to {@link ILockable.lock monopoly} the mutex, the {@link try_lock_until} - * function will call the *closure*, a custom function definig your business. After the - * *closure* function be returned, the {@link try_lock_until} function automatically - * {@link ILockable.unlock unlocks} the mutex and returns `true`, even if the *closure* - * function throws any error. - * - * TTherefore, when using this {@link try_lock_until} function, you don't need to consider - * about {@link ILockable.unlock returning} the lock acquistion after your business. It would - * just be done automatically. - * - * @param mutex Target mutex to try write lock until time expiration. - * @param at The maximum time point to wait. - * @param closure A function defining your business. - * @return Whether succeeded to monopoly the mutex or not. - * - * @throw Exception would be thrown if the *closure* function throws any error. - */ - export function try_lock_until< - Mutex extends Pick, - >(mutex: Mutex, at: Date, closure: Closure): Promise { - return SafeLock.try_lock( - () => mutex.try_lock_until(at), - () => mutex.unlock(), - closure, - ); - } + /** + * Tries to write lock a mutex with your business until time expiration. + * + * Attempts to monopoly a mutex until time expiration. If succeeded to monopoly the mutex + * until the time expiration, it returns `true` after calling the *closure*. Otherwise failed + * to acquiring the lock in the given time, the function gives up the trial and returns + * `false` without calling the *closure*. + * + * Failed to acquiring the lock in the given time (returns `false`), it means that there's + * someone who has already {@link ILockable.lock monopolied} or {@link ISharedLockable.lock} + * the mutex and does not return it over the time expiration. + * + * When succeeded to {@link ILockable.lock monopoly} the mutex, the {@link try_lock_until} + * function will call the *closure*, a custom function definig your business. After the + * *closure* function be returned, the {@link try_lock_until} function automatically + * {@link ILockable.unlock unlocks} the mutex and returns `true`, even if the *closure* + * function throws any error. + * + * TTherefore, when using this {@link try_lock_until} function, you don't need to consider + * about {@link ILockable.unlock returning} the lock acquistion after your business. It would + * just be done automatically. + * + * @param mutex Target mutex to try write lock until time expiration. + * @param at The maximum time point to wait. + * @param closure A function defining your business. + * @return Whether succeeded to monopoly the mutex or not. + * + * @throw Exception would be thrown if the *closure* function throws any error. + */ + export function try_lock_until< + Mutex extends Pick, + >(mutex: Mutex, at: Date, closure: Closure): Promise { + return SafeLock.try_lock( + () => mutex.try_lock_until(at), + () => mutex.unlock(), + closure, + ); + } - /** - * Type of closure function defining your business logic. - */ - type Closure = () => void | Promise; + /** + * Type of closure function defining your business logic. + */ + type Closure = () => void | Promise; } diff --git a/src/thread/VariadicMutableSingleton.ts b/src/thread/VariadicMutableSingleton.ts index deb249ac..bb4c7430 100644 --- a/src/thread/VariadicMutableSingleton.ts +++ b/src/thread/VariadicMutableSingleton.ts @@ -1,13 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ import { HashMap } from "../container/HashMap"; -import { MutableSingleton } from "./MutableSingleton"; -import { equal } from "../ranges/algorithm/iterations"; import { hash } from "../functional/hash"; +import { equal } from "../ranges/algorithm/iterations"; +import { MutableSingleton } from "./MutableSingleton"; /** * Variadic mutable singleton generator. @@ -15,70 +16,66 @@ import { hash } from "../functional/hash"; * @author Jeongho Nam - https://github.com/samchon */ export class VariadicMutableSingleton { - /** - * @hidden - */ - private readonly closure_: (...args: Args) => Promise; + /** + * @hidden + */ + private readonly closure_: (...args: Args) => Promise; - /** - * @hidden - */ - private readonly dict_: HashMap>; + /** + * @hidden + */ + private readonly dict_: HashMap>; - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------------- */ - public constructor( - closure: (...args: Args) => Promise, - hashFunc: (args: Args) => number = (args) => hash(...args), - pred: (x: Args, y: Args) => boolean = equal, - ) { - this.closure_ = closure; - this.dict_ = new HashMap(hashFunc, pred); - } + public constructor( + closure: (...args: Args) => Promise, + hashFunc: (args: Args) => number = (args) => hash(...args), + pred: (x: Args, y: Args) => boolean = equal, + ) { + this.closure_ = closure; + this.dict_ = new HashMap(hashFunc, pred); + } - public set(...items: [...Args, T]): Promise { - const args: Args = items.slice(0, items.length - 1) as Args; - const value: T = items[items.length - 1]; + public set(...items: [...Args, T]): Promise { + const args: Args = items.slice(0, items.length - 1) as Args; + const value: T = items[items.length - 1]; - return this._Get_singleton(args).set(value); - } + return this._Get_singleton(args).set(value); + } - public reload(...args: Args): Promise { - return this._Get_singleton(args).reload(...args); - } + public reload(...args: Args): Promise { + return this._Get_singleton(args).reload(...args); + } - public clear(): Promise; - public clear(...args: Args): Promise; - public async clear(...args: Args): Promise { - if (args.length === 0) this.dict_.clear(); - else await this._Get_singleton(args).clear(); - } + public clear(): Promise; + public clear(...args: Args): Promise; + public async clear(...args: Args): Promise { + if (args.length === 0) this.dict_.clear(); + else await this._Get_singleton(args).clear(); + } - /* --------------------------------------------------------------- + /* --------------------------------------------------------------- ACCESSORS --------------------------------------------------------------- */ - public get(...args: Args): Promise { - return this._Get_singleton(args).get(...args); - } + public get(...args: Args): Promise { + return this._Get_singleton(args).get(...args); + } - public is_loaded(...args: Args): Promise { - return this._Get_singleton(args).is_loaded(); - } + public is_loaded(...args: Args): Promise { + return this._Get_singleton(args).is_loaded(); + } - /** - * @hidden - */ - private _Get_singleton(args: Args): MutableSingleton { - let it: HashMap.Iterator< - Args, - MutableSingleton - > = this.dict_.find(args); - if (it.equals(this.dict_.end()) === true) - it = this.dict_.emplace( - args, - new MutableSingleton(this.closure_), - ).first; - return it.second; - } + /** + * @hidden + */ + private _Get_singleton(args: Args): MutableSingleton { + let it: HashMap.Iterator> = this.dict_.find( + args, + ); + if (it.equals(this.dict_.end()) === true) + it = this.dict_.emplace(args, new MutableSingleton(this.closure_)).first; + return it.second; + } } diff --git a/src/thread/VariadicSingleton.ts b/src/thread/VariadicSingleton.ts index c2bae7eb..96cddb56 100644 --- a/src/thread/VariadicSingleton.ts +++ b/src/thread/VariadicSingleton.ts @@ -1,13 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { Singleton } from "./Singleton"; import { HashMap } from "../container/HashMap"; import { hash } from "../functional/hash"; import { equal } from "../ranges/algorithm/iterations"; +import { Singleton } from "./Singleton"; /** * Variadic singleton generator. @@ -15,24 +16,22 @@ import { equal } from "../ranges/algorithm/iterations"; * @author Jeongho Nam - https://github.comm/samchon */ export class VariadicSingleton { - private readonly closure_: (...args: Args) => T; - private readonly dict_: HashMap>; + private readonly closure_: (...args: Args) => T; + private readonly dict_: HashMap>; - public constructor( - closure: (...args: Args) => T, - hashFunc: (args: Args) => number = (args) => hash(...args), - pred: (x: Args, y: Args) => boolean = equal, - ) { - this.closure_ = closure; - this.dict_ = new HashMap(hashFunc, pred); - } + public constructor( + closure: (...args: Args) => T, + hashFunc: (args: Args) => number = (args) => hash(...args), + pred: (x: Args, y: Args) => boolean = equal, + ) { + this.closure_ = closure; + this.dict_ = new HashMap(hashFunc, pred); + } - public get(...args: Args): T { - let it: HashMap.Iterator> = this.dict_.find( - args, - ); - if (it.equals(this.dict_.end()) == true) - it = this.dict_.emplace(args, new Singleton(this.closure_)).first; - return it.second.get(...args); - } + public get(...args: Args): T { + let it: HashMap.Iterator> = this.dict_.find(args); + if (it.equals(this.dict_.end()) == true) + it = this.dict_.emplace(args, new Singleton(this.closure_)).first; + return it.second.get(...args); + } } diff --git a/src/thread/VariadicTimedSingleton.ts b/src/thread/VariadicTimedSingleton.ts index 1053dfe1..18354128 100644 --- a/src/thread/VariadicTimedSingleton.ts +++ b/src/thread/VariadicTimedSingleton.ts @@ -1,7 +1,7 @@ import { HashMap } from "../container/HashMap"; -import { TimedSingleton } from "./TimedSingleton"; -import { equal } from "../ranges/algorithm/iterations"; import { hash } from "../functional/hash"; +import { equal } from "../ranges/algorithm/iterations"; +import { TimedSingleton } from "./TimedSingleton"; /** * Variadic timed singleton generator. @@ -15,47 +15,46 @@ import { hash } from "../functional/hash"; * @author Jeongho Nam - https://github.com/samchon */ export class VariadicTimedSingleton { - private readonly interval_: number; - private readonly closure_: (...args: Args) => T; - private readonly dict_: HashMap>; + private readonly interval_: number; + private readonly closure_: (...args: Args) => T; + private readonly dict_: HashMap>; - /** - * Initializer Constructor. - * - * @param interval Specific interval time, to determine whether re-generation of the singleton value is required or not, as milliseconds - * @param closure Lazy constructor function returning the target value - * @param hasher Hash function for the *lazy constructor* function arguments - * @param pred Predicator function for the *lazy constructor* function arguments - */ - public constructor( - interval: number, - closure: (...args: Args) => T, - hasher: (args: Args) => number = (args) => hash(...args), - pred: (x: Args, y: Args) => boolean = equal, - ) { - this.interval_ = interval; - this.closure_ = closure; - this.dict_ = new HashMap(hasher, pred); - } + /** + * Initializer Constructor. + * + * @param interval Specific interval time, to determine whether re-generation of the singleton value is required or not, as milliseconds + * @param closure Lazy constructor function returning the target value + * @param hasher Hash function for the *lazy constructor* function arguments + * @param pred Predicator function for the *lazy constructor* function arguments + */ + public constructor( + interval: number, + closure: (...args: Args) => T, + hasher: (args: Args) => number = (args) => hash(...args), + pred: (x: Args, y: Args) => boolean = equal, + ) { + this.interval_ = interval; + this.closure_ = closure; + this.dict_ = new HashMap(hasher, pred); + } - /** - * Get value. - * - * @param args Parameters for the lazy constructor function - * @returns The lazy constructed value - */ - public get(...args: Args): T { - let it: HashMap.Iterator< - Args, - TimedSingleton - > = this.dict_.find(args); - if (it.equals(this.dict_.end()) == true) { - const singleton: TimedSingleton = new TimedSingleton( - this.interval_, - this.closure_, - ); - it = this.dict_.emplace(args, singleton).first; - } - return it.second.get(...args); + /** + * Get value. + * + * @param args Parameters for the lazy constructor function + * @returns The lazy constructed value + */ + public get(...args: Args): T { + let it: HashMap.Iterator> = this.dict_.find( + args, + ); + if (it.equals(this.dict_.end()) == true) { + const singleton: TimedSingleton = new TimedSingleton( + this.interval_, + this.closure_, + ); + it = this.dict_.emplace(args, singleton).first; } + return it.second.get(...args); + } } diff --git a/src/thread/global.ts b/src/thread/global.ts index f05086eb..082d6fc3 100644 --- a/src/thread/global.ts +++ b/src/thread/global.ts @@ -1,4 +1,5 @@ //================================================================ + /** * @packageDocumentation * @module std @@ -12,9 +13,9 @@ import { ILockable } from "../base/thread/ILockable"; * @param ms The milliseconds to sleep. */ export function sleep_for(ms: number): Promise { - return new Promise((resolve) => { - setTimeout(resolve, ms); - }); + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); } /** @@ -23,10 +24,10 @@ export function sleep_for(ms: number): Promise { * @param at The time point to wake up. */ export function sleep_until(at: Date): Promise { - const now: Date = new Date(); - const ms: number = at.getTime() - now.getTime(); // MILLISECONDS TO WAIT + const now: Date = new Date(); + const ms: number = at.getTime() - now.getTime(); // MILLISECONDS TO WAIT - return sleep_for(ms); // CONVERT TO THE SLEEP_FOR + return sleep_for(ms); // CONVERT TO THE SLEEP_FOR } /** @@ -35,10 +36,10 @@ export function sleep_until(at: Date): Promise { * @param items Items to lock. */ export async function lock(...items: Pick[]): Promise { - const promises: Promise[] = []; - for (const mtx of items) promises.push(mtx.lock()); + const promises: Promise[] = []; + for (const mtx of items) promises.push(mtx.lock()); - await Promise.all(promises); + await Promise.all(promises); } /** @@ -48,10 +49,10 @@ export async function lock(...items: Pick[]): Promise { * @return Index of mutex who failed to lock. None of them're failed, then returns `-1`. */ export async function try_lock( - ...items: Pick[] + ...items: Pick[] ): Promise { - for (let i: number = 0; i < items.length; ++i) - if ((await items[i].try_lock()) === false) return i; + for (let i: number = 0; i < items.length; ++i) + if ((await items[i].try_lock()) === false) return i; - return -1; + return -1; } diff --git a/src/utility/Entry.ts b/src/utility/Entry.ts index 68839a74..87709bea 100644 --- a/src/utility/Entry.ts +++ b/src/utility/Entry.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IPair } from "./IPair"; import { IComparable } from "../functional/IComparable"; - +import { equal_to, less as less_fn } from "../functional/comparators"; import { hash } from "../functional/hash"; -import { less as less_fn, equal_to } from "../functional/comparators"; +import { IPair } from "./IPair"; /** * Entry for mapping. @@ -16,47 +16,47 @@ import { less as less_fn, equal_to } from "../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export class Entry - implements Readonly>, IComparable> + implements Readonly>, IComparable> { - /** - * The first, key element. - */ - public readonly first: Key; + /** + * The first, key element. + */ + public readonly first: Key; - /** - * The second, mapped element. - */ - public second: T; + /** + * The second, mapped element. + */ + public second: T; - /** - * Intializer Constructor. - * - * @param first The first, key element. - * @param second The second, mapped element. - */ - public constructor(first: Key, second: T) { - this.first = first; - this.second = second; - } + /** + * Intializer Constructor. + * + * @param first The first, key element. + * @param second The second, mapped element. + */ + public constructor(first: Key, second: T) { + this.first = first; + this.second = second; + } - /** - * @inheritDoc - */ - public equals(obj: Entry): boolean { - return equal_to(this.first, obj.first); - } + /** + * @inheritDoc + */ + public equals(obj: Entry): boolean { + return equal_to(this.first, obj.first); + } - /** - * @inheritDoc - */ - public less(obj: Entry): boolean { - return less_fn(this.first, obj.first); - } + /** + * @inheritDoc + */ + public less(obj: Entry): boolean { + return less_fn(this.first, obj.first); + } - /** - * @inheritDoc - */ - public hashCode(): number { - return hash(this.first); - } + /** + * @inheritDoc + */ + public hashCode(): number { + return hash(this.first); + } } diff --git a/src/utility/IPair.ts b/src/utility/IPair.ts index 039dc4c3..e232221a 100644 --- a/src/utility/IPair.ts +++ b/src/utility/IPair.ts @@ -10,13 +10,13 @@ * @author Jeongho Nam - https://github.com/samchon */ export interface IPair { - /** - * The first element. - */ - first: First; + /** + * The first element. + */ + first: First; - /** - * The second element. - */ - second: Second; + /** + * The second element. + */ + second: Second; } diff --git a/src/utility/Pair.ts b/src/utility/Pair.ts index d714d401..a4db46a4 100644 --- a/src/utility/Pair.ts +++ b/src/utility/Pair.ts @@ -1,14 +1,14 @@ //================================================================ + /** * @packageDocumentation * @module std */ //================================================================ -import { IPair } from "./IPair"; import { IComparable } from "../functional/IComparable"; - +import { equal_to, less } from "../functional/comparators"; import { hash } from "../functional/hash"; -import { less, equal_to } from "../functional/comparators"; +import { IPair } from "./IPair"; /** * Pair of two elements. @@ -16,64 +16,63 @@ import { less, equal_to } from "../functional/comparators"; * @author Jeongho Nam - https://github.com/samchon */ export class Pair - implements IPair, IComparable> + implements IPair, IComparable> { - /** - * @inheritDoc - */ - public first: First; + /** + * @inheritDoc + */ + public first: First; - /** - * @inheritDoc - */ - public second: Second; + /** + * @inheritDoc + */ + public second: Second; - /* --------------------------------------------------------- + /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ - /** - * Initializer Constructor. - * - * @param first The first element. - * @param second The second element. - */ - public constructor(first: First, second: Second) { - this.first = first; - this.second = second; - } + /** + * Initializer Constructor. + * + * @param first The first element. + * @param second The second element. + */ + public constructor(first: First, second: Second) { + this.first = first; + this.second = second; + } - /* --------------------------------------------------------- + /* --------------------------------------------------------- COMPARISON --------------------------------------------------------- */ - /** - * @inheritDoc - */ - public equals( - pair: Pair, - ): boolean { - return ( - equal_to(this.first, pair.first) && - equal_to(this.second, pair.second) - ); - } + /** + * @inheritDoc + */ + public equals( + pair: Pair, + ): boolean { + return ( + equal_to(this.first, pair.first) && equal_to(this.second, pair.second) + ); + } - /** - * @inheritDoc - */ - public less( - pair: Pair, - ): boolean { - if (equal_to(this.first, pair.first) === false) - return less(this.first, pair.first); - else return less(this.second, pair.second); - } + /** + * @inheritDoc + */ + public less( + pair: Pair, + ): boolean { + if (equal_to(this.first, pair.first) === false) + return less(this.first, pair.first); + else return less(this.second, pair.second); + } - /** - * @inheritDoc - */ - public hashCode(): number { - return hash(this.first, this.second); - } + /** + * @inheritDoc + */ + public hashCode(): number { + return hash(this.first, this.second); + } } /** @@ -85,8 +84,8 @@ export class Pair * @return A {@link Pair} object. */ export function make_pair( - first: First, - second: Second, + first: First, + second: Second, ): Pair { - return new Pair(first, second); + return new Pair(first, second); } diff --git a/src/utility/node.ts b/src/utility/node.ts index a80292e9..ef938fcf 100644 --- a/src/utility/node.ts +++ b/src/utility/node.ts @@ -10,24 +10,26 @@ * @return Whether NodeJS or not. */ export function is_node(): boolean { - if (is_node_ === null) - is_node_ = typeof global === "object" && is_node_process(global); - return is_node_; + if (is_node_ === null) + is_node_ = typeof global === "object" && is_node_process(global); + return is_node_; } /** * @internal */ function is_node_process(m: typeof global | null): boolean { - return m !== null && - typeof m.process === "object" && - m.process !== null && - typeof m.process.versions === "object" && - m.process.versions !== null && - typeof m.process.versions.node !== "undefined"; + return ( + m !== null && + typeof m.process === "object" && + m.process !== null && + typeof m.process.versions === "object" && + m.process.versions !== null && + typeof m.process.versions.node !== "undefined" + ); } /** * @internal */ -let is_node_: boolean | null = null; \ No newline at end of file +let is_node_: boolean | null = null; diff --git a/tsconfig.json b/tsconfig.json index 82071b86..c17e917e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,68 +1,62 @@ { - "compilerOptions": { - /* Basic Options */ - // "incremental": true, /* Enable incremental compilation */ - "target": "ES5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ - "lib": ["DOM", "ES2015"], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ - "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "./lib", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - "noUnusedLocals": true, /* Report errors on unused locals. */ - "noUnusedParameters": true, /* Report errors on unused parameters. */ - "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - "stripInternal": true, - - /* Advanced Options */ - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ - }, - "include": ["src"] + "compilerOptions": { + /* Basic Options */ + // "incremental": true, /* Enable incremental compilation */ + "target": "ES5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + "lib": ["DOM", "ES2015"], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./lib", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + /* Additional Checks */ + "noUnusedLocals": true, /* Report errors on unused locals. */ + "noUnusedParameters": true, /* Report errors on unused parameters. */ + "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + "stripInternal": true, + /* Advanced Options */ + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + }, + "include": ["src"] } From 3369f998b7c4ed514fce8ca142a05ed0552e753a Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Fri, 29 Mar 2024 02:10:52 +0900 Subject: [PATCH 2/2] Fix wrong json file --- package.json | 2 +- src/test/numeric/special_math/data.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 3042d4cd..a95f7cb1 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,7 @@ "benchmark": "node benchmark", "build": "rimraf lib && tsc && rollup -c", "dev": "rimraf lib && tsc --watch", - "prettier": "prettier --write ./src", + "prettier": "prettier --write ./src/**/*.ts", "test": "node lib/test" }, "devDependencies": { diff --git a/src/test/numeric/special_math/data.json b/src/test/numeric/special_math/data.json index 08f775f5..72cc7651 100644 --- a/src/test/numeric/special_math/data.json +++ b/src/test/numeric/special_math/data.json @@ -1499,5 +1499,5 @@ ["riemann_zeta", 6.36686, 1.01323], ["riemann_zeta", 7.68771, 1.00509], ["riemann_zeta", -0.724008, -0.140067], - ["clamp", 1, 6, 5, 5], -]; + ["clamp", 1, 6, 5, 5] +]