UNPKG

2.87 kBJavaScriptView Raw
1'use strict'
2
3const object = require('../utils/object')
4const string = require('../utils/string')
5
6function factory (type, config, load, typed) {
7 const 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 const doc = this.doc || {}
43 let 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 (let i = 0; i < doc.examples.length; i++) {
60 const expr = doc.examples[i]
61 desc += ' ' + expr + '\n'
62
63 let res
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 const 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 const doc = {}
99 for (const prop in json) {
100 if (prop !== 'mathjs') { // ignore mathjs field
101 doc[prop] = json[prop]
102 }
103 }
104 return new Help(doc)
105 }
106
107 /**
108 * Returns a string representation of the Help object
109 */
110 Help.prototype.valueOf = Help.prototype.toString
111
112 return Help
113}
114
115exports.name = 'Help'
116exports.path = 'type'
117exports.factory = factory