Created
June 20, 2018 14:12
-
-
Save num8er/d78b391e56b4fce22d0601b6a5fd07c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
const originalText = 'Hello World'; | |
const widgets = [ | |
{position: 2, text: '111'}, | |
{position: 4, text: '222'}, | |
{position: 6, text: '333'} | |
]; | |
Given text and widgets, need to inject widget text in positions. | |
Result must be: He111ll222o 333World | |
*/ | |
Object.assign(String.prototype, { | |
injectWidgets(widgets) { | |
const parts = []; | |
const text = this.toString(); | |
let lastPosition = 0; | |
widgets.forEach(widget => { | |
parts.push(text.substr(lastPosition, widget.position - lastPosition)); | |
parts.push(widget.text); | |
lastPosition = widget.position; | |
}); | |
parts.push(text.substr(lastPosition)); | |
return parts.join(''); | |
} | |
}); | |
const injectedText = originalText.injectWidgets(widgets); |
faridjafarlee
commented
Feb 13, 2020
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment