1 | 'use strict'
|
2 |
|
3 | const DimensionError = require('../../error/DimensionError')
|
4 | const ArgumentsError = require('../../error/ArgumentsError')
|
5 |
|
6 | const isInteger = require('../../utils/number').isInteger
|
7 | const format = require('../../utils/string').format
|
8 | const clone = require('../../utils/object').clone
|
9 | const array = require('../../utils/array')
|
10 |
|
11 | function factory (type, config, load, typed) {
|
12 | const matrix = load(require('../../type/matrix/function/matrix'))
|
13 |
|
14 | |
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 | const resize = function resize (x, size, defaultValue) {
|
42 | if (arguments.length !== 2 && arguments.length !== 3) {
|
43 | throw new ArgumentsError('resize', arguments.length, 2, 3)
|
44 | }
|
45 |
|
46 | if (type.isMatrix(size)) {
|
47 | size = size.valueOf()
|
48 | }
|
49 |
|
50 | if (type.isBigNumber(size[0])) {
|
51 |
|
52 | size = size.map(function (value) {
|
53 | return type.isBigNumber(value) ? value.toNumber() : value
|
54 | })
|
55 | }
|
56 |
|
57 |
|
58 | if (type.isMatrix(x)) {
|
59 |
|
60 | return x.resize(size, defaultValue, true)
|
61 | }
|
62 |
|
63 | if (typeof x === 'string') {
|
64 |
|
65 | return _resizeString(x, size, defaultValue)
|
66 | }
|
67 |
|
68 |
|
69 | const asMatrix = Array.isArray(x) ? false : (config.matrix !== 'Array')
|
70 |
|
71 | if (size.length === 0) {
|
72 |
|
73 | while (Array.isArray(x)) {
|
74 | x = x[0]
|
75 | }
|
76 |
|
77 | return clone(x)
|
78 | } else {
|
79 |
|
80 | if (!Array.isArray(x)) {
|
81 | x = [x]
|
82 | }
|
83 | x = clone(x)
|
84 |
|
85 | const res = array.resize(x, size, defaultValue)
|
86 | return asMatrix ? matrix(res) : res
|
87 | }
|
88 | }
|
89 |
|
90 | resize.toTex = undefined
|
91 |
|
92 | return resize
|
93 |
|
94 | |
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 | function _resizeString (str, size, defaultChar) {
|
102 | if (defaultChar !== undefined) {
|
103 | if (typeof defaultChar !== 'string' || defaultChar.length !== 1) {
|
104 | throw new TypeError('Single character expected as defaultValue')
|
105 | }
|
106 | } else {
|
107 | defaultChar = ' '
|
108 | }
|
109 |
|
110 | if (size.length !== 1) {
|
111 | throw new DimensionError(size.length, 1)
|
112 | }
|
113 | const len = size[0]
|
114 | if (typeof len !== 'number' || !isInteger(len)) {
|
115 | throw new TypeError('Invalid size, must contain positive integers ' +
|
116 | '(size: ' + format(size) + ')')
|
117 | }
|
118 |
|
119 | if (str.length > len) {
|
120 | return str.substring(0, len)
|
121 | } else if (str.length < len) {
|
122 | let res = str
|
123 | for (let i = 0, ii = len - str.length; i < ii; i++) {
|
124 | res += defaultChar
|
125 | }
|
126 | return res
|
127 | } else {
|
128 | return str
|
129 | }
|
130 | }
|
131 | }
|
132 |
|
133 | exports.name = 'resize'
|
134 | exports.factory = factory
|