Skip to content

Instantly share code, notes, and snippets.

@num8er
Created June 20, 2018 14:12
Show Gist options
  • Save num8er/d78b391e56b4fce22d0601b6a5fd07c5 to your computer and use it in GitHub Desktop.
Save num8er/d78b391e56b4fce22d0601b6a5fd07c5 to your computer and use it in GitHub Desktop.
/*
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
Copy link

faridjafarlee commented Feb 13, 2020

widgets.forEach(function (widget, index) {
    (index === widgets.length - 1) 
      ? newWord += originalText.substring(widget.position, originalText.length) 
      : newWord += originalText.substring(widgets[index - 1] 
          ? widgets[index - 1].position 
          : lastElem, widget.position) + widget.text;
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment