如何在Javascript中相交区间?
作为输入,我有一个字符串和一个带颜色的间隔数组:如何在Javascript中相交区间?,javascript,arrays,intervals,Javascript,Arrays,Intervals,作为输入,我有一个字符串和一个带颜色的间隔数组: // 0123456789.123456789.123456789.123456789.123 const str = 'The quick brown fox jumps over the lazy dog.'; const colors = [ {from: 0, to: 8, color: 'red'}, {from: 10, to: 14, color: 'brown'}, {from: 16, t
// 0123456789.123456789.123456789.123456789.123
const str = 'The quick brown fox jumps over the lazy dog.';
const colors = [
{from: 0, to: 8, color: 'red'},
{from: 10, to: 14, color: 'brown'},
{from: 16, to: 24, color: 'blue'},
{from: 20, to: 29, color: 'yellow'}
];
请注意,输入间隔可以相交
作为输出,我想计算一个非相交的间隔数组,其中包含给定字符串中的颜色和子字符串。呼叫应如下所示:
[
{ from: 0, to: 8, sub: 'The quick', colors: ['red' ] },
{ from: 9, to: 9, sub: ' ', colors: ['defaultColor' ] },
{ from: 10, to: 14, sub: 'brown', colors: ['brown' ] },
{ from: 15, to: 15, sub: ' ', colors: ['defaultColor' ] },
{ from: 16, to: 19, sub: 'fox ', colors: ['blue' ] },
{ from: 20, to: 24, sub: 'jumps', colors: ['blue', 'yellow'] },
{ from: 25, to: 29, sub: ' over', colors: ['yellow' ] },
{ from: 30, to: 43, sub: ' the lazy dog.', colors: ['defaultColor' ] },
]
result=colorizedStrings(str,colors,'defaultColor')强>
结果应该如下所示:
[
{ from: 0, to: 8, sub: 'The quick', colors: ['red' ] },
{ from: 9, to: 9, sub: ' ', colors: ['defaultColor' ] },
{ from: 10, to: 14, sub: 'brown', colors: ['brown' ] },
{ from: 15, to: 15, sub: ' ', colors: ['defaultColor' ] },
{ from: 16, to: 19, sub: 'fox ', colors: ['blue' ] },
{ from: 20, to: 24, sub: 'jumps', colors: ['blue', 'yellow'] },
{ from: 25, to: 29, sub: ' over', colors: ['yellow' ] },
{ from: 30, to: 43, sub: ' the lazy dog.', colors: ['defaultColor' ] },
]
必要时,输出间隔包含多个颜色
我试图找到一个开源Javascript库来计算间隔交点。然而,我找不到一个简单且小的库——库中总是包含一些新奇的东西(例如图形、图表等)。我在这里寻找“纯数学”
您能帮我找到一个合适的解决方案吗?您可以映射字符并获得每个字符的颜色,然后减少此数组以获得相同颜色的簇
函数colorizedStrings(字符串、颜色、默认颜色){
返回数组
.from(string,(sub,i)=>{
var t=colors.filter({from,to})=>from{
var last=r[r.长度-1];
if(last&&last.colors.join()==colors.join()){
++最后,到;
last.sub+=sub;
}否则{
r、 推送({from:i,to:i,sub,colors});
}
返回r;
}, []);
}
// 0123456789.123456789.123456789.123456789.123
var str=“敏捷的棕色狐狸跳过了懒狗。”,
// ---------
// -----
// ---------
// ----------
colors=[{from:0,to:8,color:'red'},{from:10,to:14,color:'brown'},{from:16,to:24,color:'blue'},{from:20,to:29,color:'yellow'}],
结果=colorizedString(str,colors,'defaultColor');
console.log(结果);
。作为控制台包装{max height:100%!important;top:0;}
请添加您尝试过的内容和不起作用的内容。也请查看此处:拆分字符串的标准是什么?不清楚您的目标是什么,一些进一步的解释会有所帮助。您好@NinaScholz,我添加了一段“我尝试过…”在问题的结尾。@kiranvj标准是所得的区间不能再重叠。数字总是整数。哇,这就像预期的那样有效,非常感谢!我研究了一下,发现了代码中发生了什么。复杂性取决于string.length和colors.length。直觉上,我期待一个解决方案复杂度不取决于string.length,只取决于colors.length。但是,就我而言,这并不重要,因为我的字符串很小。我知道如果主题与数组相关,答案将来自Nina。我添加了标签,以便您注意到这个问题+1@MatthiasBohlen,也许第三种方法是wa但是它有点复杂,因为范围检查和分成两到三部分。