UNPKG

snippet-cutter

Version:

Returns a subset of a string, composed by complete subsets found using delimeter between min and max length. If no complete subsets are found, returns a subset using length max and ellipsis.

25 lines (22 loc) 650 B
var defaults = require('lodash.defaults') var defaultOptions = { min: 1, max: 140, ellipsis: '...', delimeter: '.' } module.exports = function snippetCutter (str, opts) { const options = defaults({}, opts, defaultOptions) return str.split(options.delimeter).reduce((snippet, sentence) => { if (options.min >= options.max) { options.max = options.min } if (snippet.length < options.min) { return snippet.concat(sentence + options.delimeter) } if (snippet.length > (options.max + options.ellipsis.length)) { return snippet.slice(0, options.max) + options.ellipsis } return snippet }, '') }