UNPKG

3.04 kBJavaScriptView Raw
1import { isHelp } from '../utils/is';
2import { clone } from '../utils/object';
3import { format } from '../utils/string';
4import { factory } from '../utils/factory';
5var name = 'Help';
6var dependencies = ['parse'];
7export var createHelpClass =
8/* #__PURE__ */
9factory(name, dependencies, function (_ref) {
10 var parse = _ref.parse;
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
116 for (var prop in json) {
117 if (prop !== 'mathjs') {
118 // ignore mathjs field
119 doc[prop] = json[prop];
120 }
121 }
122
123 return new Help(doc);
124 };
125 /**
126 * Returns a string representation of the Help object
127 */
128
129
130 Help.prototype.valueOf = Help.prototype.toString;
131 return Help;
132}, {
133 isClass: true
134});
\No newline at end of file