UNPKG

3.02 kBJavaScriptView Raw
1import { isHelp } from '../utils/is.js';
2import { clone } from '../utils/object.js';
3import { format } from '../utils/string.js';
4import { factory } from '../utils/factory.js';
5var name = 'Help';
6var dependencies = ['parse'];
7export var createHelpClass = /* #__PURE__ */factory(name, dependencies, (_ref) => {
8 var {
9 parse
10 } = _ref;
11
12 /**
13 * Documentation object
14 * @param {Object} doc Object containing properties:
15 * {string} name
16 * {string} category
17 * {string} description
18 * {string[]} syntax
19 * {string[]} examples
20 * {string[]} seealso
21 * @constructor
22 */
23 function Help(doc) {
24 if (!(this instanceof Help)) {
25 throw new SyntaxError('Constructor must be called with the new operator');
26 }
27
28 if (!doc) throw new Error('Argument "doc" missing');
29 this.doc = doc;
30 }
31 /**
32 * Attach type information
33 */
34
35
36 Help.prototype.type = 'Help';
37 Help.prototype.isHelp = true;
38 /**
39 * Generate a string representation of the Help object
40 * @return {string} Returns a string
41 * @private
42 */
43
44 Help.prototype.toString = function () {
45 var doc = this.doc || {};
46 var desc = '\n';
47
48 if (doc.name) {
49 desc += 'Name: ' + doc.name + '\n\n';
50 }
51
52 if (doc.category) {
53 desc += 'Category: ' + doc.category + '\n\n';
54 }
55
56 if (doc.description) {
57 desc += 'Description:\n ' + doc.description + '\n\n';
58 }
59
60 if (doc.syntax) {
61 desc += 'Syntax:\n ' + doc.syntax.join('\n ') + '\n\n';
62 }
63
64 if (doc.examples) {
65 desc += 'Examples:\n';
66 var scope = {};
67
68 for (var i = 0; i < doc.examples.length; i++) {
69 var expr = doc.examples[i];
70 desc += ' ' + expr + '\n';
71 var res = void 0;
72
73 try {
74 // note: res can be undefined when `expr` is an empty string
75 res = parse(expr).compile().evaluate(scope);
76 } catch (e) {
77 res = e;
78 }
79
80 if (res !== undefined && !isHelp(res)) {
81 desc += ' ' + format(res, {
82 precision: 14
83 }) + '\n';
84 }
85 }
86
87 desc += '\n';
88 }
89
90 if (doc.seealso && doc.seealso.length) {
91 desc += 'See also: ' + doc.seealso.join(', ') + '\n';
92 }
93
94 return desc;
95 };
96 /**
97 * Export the help object to JSON
98 */
99
100
101 Help.prototype.toJSON = function () {
102 var obj = clone(this.doc);
103 obj.mathjs = 'Help';
104 return obj;
105 };
106 /**
107 * Instantiate a Help object from a JSON object
108 * @param {Object} json
109 * @returns {Help} Returns a new Help object
110 */
111
112
113 Help.fromJSON = function (json) {
114 var doc = {};
115 Object.keys(json).filter(prop => prop !== 'mathjs').forEach(prop => {
116 doc[prop] = json[prop];
117 });
118 return new Help(doc);
119 };
120 /**
121 * Returns a string representation of the Help object
122 */
123
124
125 Help.prototype.valueOf = Help.prototype.toString;
126 return Help;
127}, {
128 isClass: true
129});
\No newline at end of file