Skip to content

Commit 238dde2

Browse files
committed
Remove exception on non-node
1 parent 4696d3b commit 238dde2

File tree

2 files changed

+19
-12
lines changed

2 files changed

+19
-12
lines changed

index.js

+17-9
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,27 @@
22

33
module.exports = toString
44

5-
// Get the text content of a node. If the node itself does not expose
6-
// plain-text fields, `toString` will recursivly try its children.
5+
// Get the text content of a node.
6+
// Prefer the node’s plain-text fields, otherwise serialize its children.
77
function toString(node) {
88
return (
9-
valueOf(node) ||
10-
(node.children && node.children.map(toString).join('')) ||
9+
(node &&
10+
(node.value ||
11+
node.alt ||
12+
node.title ||
13+
('children' in node && all(node.children)))) ||
1114
''
1215
)
1316
}
1417

15-
// Get the value of `node`. Checks, `value`, `alt`, and `title`, in that order.
16-
function valueOf(node) {
17-
return (
18-
(node && node.value ? node.value : node.alt ? node.alt : node.title) || ''
19-
)
18+
function all(values) {
19+
var result = []
20+
var length = values.length
21+
var index = -1
22+
23+
while (++index < length) {
24+
result[index] = toString(values[index])
25+
}
26+
27+
return result.join('')
2028
}

test.js

+2-3
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@ var test = require('tape')
44
var toString = require('.')
55

66
test('mdast-util-to-string', function(t) {
7-
t.throws(function() {
8-
toString()
9-
}, 'should fail without node')
7+
t.equal(toString(), '', 'should not fail on a missing node')
8+
t.equal(toString(null), '', 'should not fail on `null` missing node')
109

1110
t.equal(
1211
toString({value: 'foo'}),

0 commit comments

Comments
 (0)