There is the following piece of code that I would like to reduce to a more concise form. I think I did not make the best decision at all. Simultaneously getting rid of the bug, which consists in limiting the operation of the program from arrays prescribed in advance in the code. Please tell me how it can be done. Jquery library 3.5.1
function FaendKey(arr){
var Key = [];
for (zz = 0; zz < arr.length; zz ) {
if (fileSystem[zz].name == arr[0]) {
Key.push(zz);
break;
}
}
if (arr.length > 2) {
var arrKeyOld = fileSystem[Key[0]].items;
for (z = 1; z < arr.length-1; z ) {
var tickKey = FaendKeyOld(arr[z],arrKeyOld);
Key.push(tickKey);
arrKeyOld = arrKeyOld[tickKey].items;
}
}
return Key;
}
function onSuccess(data){
for (k = 0; k < data.d.results.length; k ) {
var UrlFull = data.d.results[k].ServerRelativeUrl.split('/');
UrlFull.splice(0,4);
var idKey = [];
var idKey = FaendKey(UrlFull);
if (idKey.length == 1) {
fileSystem[idKey[0]].items.push(
{
name: data.d.results[k].Name,
isDirectory: true, __KEY__: data.d.results[k].UniqueId,
dateModified: data.d.results[k].TimeLastModified,
items: [],
}
)
} else {
if (idKey.length == 2) {
fileSystem[idKey[0]].items[idKey[1]].items.push(
{
name: data.d.results[k].Name,
isDirectory: true, __KEY__: data.d.results[k].UniqueId,
dateModified: data.d.results[k].TimeLastModified,
items: [],
}
)
}
if (idKey.length == 3) {
fileSystem[idKey[0]].items[idKey[1]].items[idKey[2]].items.push(
{
name: data.d.results[k].Name,
isDirectory: true, __KEY__: data.d.results[k].UniqueId,
dateModified: data.d.results[k].TimeLastModified,
items: [],
}
)
}
.. and then a similar structure up to the value idKey.length == 10...
CodePudding user response:
you can use a recursive function for that
something like this
const saveItem = (keys, data, store) => {
if(keys.length === 1){
store.items.push(data)
return;
}
const [key, ...rest] = keys
return saveItem(rest, data, store[key])
}
than you can call it like this
function onSuccess(data){
for (k = 0; k < data.d.results.length; k ) {
var UrlFull = data.d.results[k].ServerRelativeUrl.split('/');
UrlFull.splice(0,4);
var idKey = [];
var idKey = FaendKey(UrlFull);
const data = {
name: data.d.results[k].Name,
isDirectory: true, __KEY__: data.d.results[k].UniqueId,
dateModified: data.d.results[k].TimeLastModified,
items: [],
}
saveItem(idKey, data, fileSystem)
}
}
CodePudding user response:
A use case for filter
:
var Key = [];
for (zz = 0; zz < arr.length; zz ) {
if (fileSystem[zz].name == arr[0]) {
Key.push(zz);
break;
}
try:
var Key = arr.filter(x => fileSystem[x].name == arr[0])