javascript - Merging issue between array and string -
i have array containing letters , colors.
const = [ {char: 'h', color: 'red'}, {char: 'e', color: 'red'}, {char: 'y', color: 'red'}, {char: ' ', color: 'green'}, {char: 't', color: 'red'}, {char: 'h', color: 'red'}, {char: 'e', color: 'red'}, {char: 'r', color: 'red'}, {char: 'e', color: 'red'} ];
i want write function merges string:
const s = 'hey, howdy there';
while preserving original mapping of chars colors. instance, chars compose hey
, there
should still red , green, painted in array a, while new chars default arbitrary, yellow , old chars deleted. so, output of function give me like:
res = [ {char: 'h', color: 'red'}, {char: 'e', color: 'red'}, {char: 'y', color: 'red'}, {char: ',', color: 'yellow'}, {char: ' ', color: 'green'}, {char: 'h', color: 'yellow'}, {char: 'o', color: 'yellow'}, {char: 'w', color: 'yellow'}, {char: 'd', color: 'yellow'}, {char: 'y', color: 'yellow'}, {char: ' ', color: 'yellow'}, {char: 't', color: 'red'}, {char: 'h', color: 'red'}, {char: 'e', color: 'red'}, {char: 'r', color: 'red'}, {char: 'e', color: 'red'} ];
one approach might extract chars const a
, join them string , split on space, have array of words. repeat string s. loop on new split array of string s until there mismatch between , original array split. happen on ,
char.
this i'm not sure how proceed. in simple case, there 2 words, can keep first word , replace else new words string s split. however, in case provided, i'm adding values new string (i.e. , howdy
) while preserving values of old array (there
).
i imagine algorithm git uses diff text work here i'm not sure how replicate it, or if efficient in use case.
edit: modified bit because realized of inconsistent.
how this?
https://jsfiddle.net/jdv9gz01/
function megajoin (orig, newword, index) { var tmparr = orig.slice(); var newwordarray = newword.split('').map((char)=>{return {char:char, color:'yellow'}}); array.prototype.splice.apply(tmparr, [index,0].concat(newwordarray)); return tmparr; }
i unsure join should happen, function uses index know should join.
if don't know newword is, function it. it's not perfect tho.
function getdifference(weirdarray, newstring) { var tmps = []; (var = 0; <= weirdarray.length; i++) { var word = a[i]; if (word && word.char !== '' && !== a.length) { tmps.push(word.char); } else { newstring = newstring.replace(tmps.join(''), ''); tmps = []; } } return newstring; }
Comments
Post a Comment