UNPKG

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