Skip to content

Commit

Permalink
feat: add html encoder
Browse files Browse the repository at this point in the history
  • Loading branch information
stfsy committed Aug 26, 2022
1 parent fea9bb4 commit d4cd798
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/html-encoder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict'

const encodeHtml = require('html-entities').encode

const encode = (object) => {
const result = {}

Object.entries(object).forEach(([key, value]) => {
if (typeof value === 'object') {
result[key] = encode(value)
} else {
result[key] = encodeHtml(value)
}
})

return result
}

module.exports = encode
22 changes: 22 additions & 0 deletions test/spec/html-encoder.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict'

const encode = require('../../lib/html-encoder')

const { expect } = require('chai')

describe('HtmlEncoder', () => {
it('encodes recursively', () => {
const object = {
nested1: {
nested2: {
left: '<',
right: '>'
}
}
}

const encoded = encode(object)
expect(encoded.nested1.nested2.left).to.equal('&lt;')
expect(encoded.nested1.nested2.right).to.equal('&gt;')
})
})

0 comments on commit d4cd798

Please sign in to comment.