arrays - 解析电子表格结构中的简单引用。这是一个链表问题吗?
问题描述
我有这个工作测试任务,我需要一些帮助。
我必须通过引用以某种方式动态访问下面数据结构中的值。到目前为止,我使用了循环和indexOf()
有序的字母和数字。indexOf("B")
在字母表中是[[ 1 ]]
,indexOf(1)
是[0]
为二维数组。
这里“B1”引用“C1”,“C1”引用“D1”..指向“H1”,当“H1”指向文本“Last”时,所有公式都应该变成相同的值 - 文本“最后的”。
但是怎么做?花了几个小时才想起了链表,但到目前为止还不知道如何实现它们。我怎样才能做到这一点?
{
data: [
[
{ reference: "B1" },
{ reference: "C1" },
{ reference: "D1" },
{ reference: "E1" },
{ reference: "F1" },
{ reference: "G1" },
{ reference: "H1" },
{ text: "Last" },
]
],
id: "job-20"
}
解决方案
看起来您需要使用电子表格类型的数据结构,并且需要根据它们拥有的公式重新计算单元格。
您可以为此使用递归。
基本情况发生在您到达没有参考的单元格时。在这种情况下,该单元格的文本可以返回给调用者。并且该调用者将该文本分配给它正在查看的单元格,并将其返回给他们的调用者......等等。
function get(reference) { // return the cell object at the given reference
return data[reference.slice(1)-1][reference.charCodeAt() - "A".charCodeAt()];
}
function resolve(cell, visited=new Set) {
// Have we found a cell with just text? Then return that to caller
if (!("reference" in cell)) return cell.text;
// Did we already meet this cell before? Then we are running in circles!
if (visited.has(cell)) return "Circular Reference!";
// Make a recursive call to know what the text should be
cell.text = resolve(get(cell.reference), visited.add(cell));
delete cell.reference;
return cell.text; // Return this value also to the caller
}
function calculate(data) {
// Get to each cell object...
for (let row of data) {
for (let cell of row) {
resolve(cell); // And update its text property by following references
}
}
}
let data = [
[
{reference: "B1"}, {reference: "C1"}, {reference: "D1"}, {reference: "E1"},
{reference: "F1"}, {reference: "G1"}, {reference: "H1"}, {text: "Last"},
]
];
calculate(data);
console.log(data);
应该注意的是,在真实的电子表格中,在重新计算期间不会删除参考(公式)。该单元格将同时具有文本和引用,因此当单元格的文本更新时,所有其他相关单元格都会相应地再次更新自己的文本。
推荐阅读
- swift - Swift 5 Conversion UnsafeBufferPointer 的这些内存功能是否相同
- r - 使用融化功能
- python - 在 Pandas 中为一组列设置新值
- mysql - Loopback 3 - 删除或编辑涉及映射表的嵌套模型
- javascript - 使用 .map 函数获取数据数组
- python - 如何将ajax发送的blob转换为python烧瓶中的音频文件
- sql - 如何使用运行总计加快选择查询?
- graphql - 使用 Graphql 查询 API 时出现“无法返回 null”错误?
- git - 区分工作树文件夹的git命令是什么
- amazon-web-services - 如何使用 CloudWatch 事件将 CodeCommit 标签名称传递给 CodePipeline