UNPKG

8.66 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.createRangeClass = void 0;
7
8var _is = require("../../utils/is.js");
9
10var _number = require("../../utils/number.js");
11
12var _factory = require("../../utils/factory.js");
13
14var name = 'Range';
15var dependencies = [];
16var createRangeClass = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function () {
17 /**
18 * Create a range. A range has a start, step, and end, and contains functions
19 * to iterate over the range.
20 *
21 * A range can be constructed as:
22 *
23 * const range = new Range(start, end)
24 * const range = new Range(start, end, step)
25 *
26 * To get the result of the range:
27 * range.forEach(function (x) {
28 * console.log(x)
29 * })
30 * range.map(function (x) {
31 * return math.sin(x)
32 * })
33 * range.toArray()
34 *
35 * Example usage:
36 *
37 * const c = new Range(2, 6) // 2:1:5
38 * c.toArray() // [2, 3, 4, 5]
39 * const d = new Range(2, -3, -1) // 2:-1:-2
40 * d.toArray() // [2, 1, 0, -1, -2]
41 *
42 * @class Range
43 * @constructor Range
44 * @param {number} start included lower bound
45 * @param {number} end excluded upper bound
46 * @param {number} [step] step size, default value is 1
47 */
48 function Range(start, end, step) {
49 if (!(this instanceof Range)) {
50 throw new SyntaxError('Constructor must be called with the new operator');
51 }
52
53 var hasStart = start !== null && start !== undefined;
54 var hasEnd = end !== null && end !== undefined;
55 var hasStep = step !== null && step !== undefined;
56
57 if (hasStart) {
58 if ((0, _is.isBigNumber)(start)) {
59 start = start.toNumber();
60 } else if (typeof start !== 'number') {
61 throw new TypeError('Parameter start must be a number');
62 }
63 }
64
65 if (hasEnd) {
66 if ((0, _is.isBigNumber)(end)) {
67 end = end.toNumber();
68 } else if (typeof end !== 'number') {
69 throw new TypeError('Parameter end must be a number');
70 }
71 }
72
73 if (hasStep) {
74 if ((0, _is.isBigNumber)(step)) {
75 step = step.toNumber();
76 } else if (typeof step !== 'number') {
77 throw new TypeError('Parameter step must be a number');
78 }
79 }
80
81 this.start = hasStart ? parseFloat(start) : 0;
82 this.end = hasEnd ? parseFloat(end) : 0;
83 this.step = hasStep ? parseFloat(step) : 1;
84 }
85 /**
86 * Attach type information
87 */
88
89
90 Range.prototype.type = 'Range';
91 Range.prototype.isRange = true;
92 /**
93 * Parse a string into a range,
94 * The string contains the start, optional step, and end, separated by a colon.
95 * If the string does not contain a valid range, null is returned.
96 * For example str='0:2:11'.
97 * @memberof Range
98 * @param {string} str
99 * @return {Range | null} range
100 */
101
102 Range.parse = function (str) {
103 if (typeof str !== 'string') {
104 return null;
105 }
106
107 var args = str.split(':');
108 var nums = args.map(function (arg) {
109 return parseFloat(arg);
110 });
111 var invalid = nums.some(function (num) {
112 return isNaN(num);
113 });
114
115 if (invalid) {
116 return null;
117 }
118
119 switch (nums.length) {
120 case 2:
121 return new Range(nums[0], nums[1]);
122
123 case 3:
124 return new Range(nums[0], nums[2], nums[1]);
125
126 default:
127 return null;
128 }
129 };
130 /**
131 * Create a clone of the range
132 * @return {Range} clone
133 */
134
135
136 Range.prototype.clone = function () {
137 return new Range(this.start, this.end, this.step);
138 };
139 /**
140 * Retrieve the size of the range.
141 * Returns an array containing one number, the number of elements in the range.
142 * @memberof Range
143 * @returns {number[]} size
144 */
145
146
147 Range.prototype.size = function () {
148 var len = 0;
149 var start = this.start;
150 var step = this.step;
151 var end = this.end;
152 var diff = end - start;
153
154 if ((0, _number.sign)(step) === (0, _number.sign)(diff)) {
155 len = Math.ceil(diff / step);
156 } else if (diff === 0) {
157 len = 0;
158 }
159
160 if (isNaN(len)) {
161 len = 0;
162 }
163
164 return [len];
165 };
166 /**
167 * Calculate the minimum value in the range
168 * @memberof Range
169 * @return {number | undefined} min
170 */
171
172
173 Range.prototype.min = function () {
174 var size = this.size()[0];
175
176 if (size > 0) {
177 if (this.step > 0) {
178 // positive step
179 return this.start;
180 } else {
181 // negative step
182 return this.start + (size - 1) * this.step;
183 }
184 } else {
185 return undefined;
186 }
187 };
188 /**
189 * Calculate the maximum value in the range
190 * @memberof Range
191 * @return {number | undefined} max
192 */
193
194
195 Range.prototype.max = function () {
196 var size = this.size()[0];
197
198 if (size > 0) {
199 if (this.step > 0) {
200 // positive step
201 return this.start + (size - 1) * this.step;
202 } else {
203 // negative step
204 return this.start;
205 }
206 } else {
207 return undefined;
208 }
209 };
210 /**
211 * Execute a callback function for each value in the range.
212 * @memberof Range
213 * @param {function} callback The callback method is invoked with three
214 * parameters: the value of the element, the index
215 * of the element, and the Range being traversed.
216 */
217
218
219 Range.prototype.forEach = function (callback) {
220 var x = this.start;
221 var step = this.step;
222 var end = this.end;
223 var i = 0;
224
225 if (step > 0) {
226 while (x < end) {
227 callback(x, [i], this);
228 x += step;
229 i++;
230 }
231 } else if (step < 0) {
232 while (x > end) {
233 callback(x, [i], this);
234 x += step;
235 i++;
236 }
237 }
238 };
239 /**
240 * Execute a callback function for each value in the Range, and return the
241 * results as an array
242 * @memberof Range
243 * @param {function} callback The callback method is invoked with three
244 * parameters: the value of the element, the index
245 * of the element, and the Matrix being traversed.
246 * @returns {Array} array
247 */
248
249
250 Range.prototype.map = function (callback) {
251 var array = [];
252 this.forEach(function (value, index, obj) {
253 array[index[0]] = callback(value, index, obj);
254 });
255 return array;
256 };
257 /**
258 * Create an Array with a copy of the Ranges data
259 * @memberof Range
260 * @returns {Array} array
261 */
262
263
264 Range.prototype.toArray = function () {
265 var array = [];
266 this.forEach(function (value, index) {
267 array[index[0]] = value;
268 });
269 return array;
270 };
271 /**
272 * Get the primitive value of the Range, a one dimensional array
273 * @memberof Range
274 * @returns {Array} array
275 */
276
277
278 Range.prototype.valueOf = function () {
279 // TODO: implement a caching mechanism for range.valueOf()
280 return this.toArray();
281 };
282 /**
283 * Get a string representation of the range, with optional formatting options.
284 * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11'
285 * @memberof Range
286 * @param {Object | number | function} [options] Formatting options. See
287 * lib/utils/number:format for a
288 * description of the available
289 * options.
290 * @returns {string} str
291 */
292
293
294 Range.prototype.format = function (options) {
295 var str = (0, _number.format)(this.start, options);
296
297 if (this.step !== 1) {
298 str += ':' + (0, _number.format)(this.step, options);
299 }
300
301 str += ':' + (0, _number.format)(this.end, options);
302 return str;
303 };
304 /**
305 * Get a string representation of the range.
306 * @memberof Range
307 * @returns {string}
308 */
309
310
311 Range.prototype.toString = function () {
312 return this.format();
313 };
314 /**
315 * Get a JSON representation of the range
316 * @memberof Range
317 * @returns {Object} Returns a JSON object structured as:
318 * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}`
319 */
320
321
322 Range.prototype.toJSON = function () {
323 return {
324 mathjs: 'Range',
325 start: this.start,
326 end: this.end,
327 step: this.step
328 };
329 };
330 /**
331 * Instantiate a Range from a JSON object
332 * @memberof Range
333 * @param {Object} json A JSON object structured as:
334 * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}`
335 * @return {Range}
336 */
337
338
339 Range.fromJSON = function (json) {
340 return new Range(json.start, json.end, json.step);
341 };
342
343 return Range;
344}, {
345 isClass: true
346});
347exports.createRangeClass = createRangeClass;
\No newline at end of file