Skip to content

Commit

Permalink
Remove exception on non-node
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Mar 8, 2020
1 parent 4696d3b commit 238dde2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
26 changes: 17 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,27 @@

module.exports = toString

// Get the text content of a node. If the node itself does not expose
// plain-text fields, `toString` will recursivly try its children.
// Get the text content of a node.
// Prefer the node’s plain-text fields, otherwise serialize its children.
function toString(node) {
return (
valueOf(node) ||
(node.children && node.children.map(toString).join('')) ||
(node &&
(node.value ||
node.alt ||
node.title ||
('children' in node && all(node.children)))) ||
''
)
}

// Get the value of `node`. Checks, `value`, `alt`, and `title`, in that order.
function valueOf(node) {
return (
(node && node.value ? node.value : node.alt ? node.alt : node.title) || ''
)
function all(values) {
var result = []
var length = values.length
var index = -1

while (++index < length) {
result[index] = toString(values[index])
}

return result.join('')
}
5 changes: 2 additions & 3 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ var test = require('tape')
var toString = require('.')

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

t.equal(
toString({value: 'foo'}),
Expand Down

0 comments on commit 238dde2

Please sign in to comment.