Mathias Bynens | 79e2cf0 | 2020-05-29 16:46:17 +0200 | [diff] [blame] | 1 | 'use strict'; |
| 2 | const isRegexp = require('is-regexp'); |
| 3 | |
| 4 | const flagMap = { |
| 5 | global: 'g', |
| 6 | ignoreCase: 'i', |
| 7 | multiline: 'm', |
| 8 | dotAll: 's', |
| 9 | sticky: 'y', |
| 10 | unicode: 'u' |
| 11 | }; |
| 12 | |
| 13 | module.exports = (regexp, options = {}) => { |
| 14 | if (!isRegexp(regexp)) { |
| 15 | throw new TypeError('Expected a RegExp instance'); |
| 16 | } |
| 17 | |
| 18 | const flags = Object.keys(flagMap).map(flag => ( |
| 19 | (typeof options[flag] === 'boolean' ? options[flag] : regexp[flag]) ? flagMap[flag] : '' |
| 20 | )).join(''); |
| 21 | |
| 22 | const clonedRegexp = new RegExp(options.source || regexp.source, flags); |
| 23 | |
| 24 | clonedRegexp.lastIndex = typeof options.lastIndex === 'number' ? |
| 25 | options.lastIndex : |
| 26 | regexp.lastIndex; |
| 27 | |
| 28 | return clonedRegexp; |
| 29 | }; |