fix accessWithInit helper function

This commit is contained in:
Tobias Koppers 2020-02-26 16:13:38 +01:00
parent 88e6c5e2a7
commit ed097f08d9
1 changed files with 28 additions and 6 deletions

View File

@ -29,21 +29,43 @@ const accessWithInit = (accessor, existingLength, initLast = false) => {
// This generates for [a, b, c, d]:
// (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d
const base = accessor[0];
if (accessor.length === 1 && !initLast) return base;
let current =
existingLength > 0 || (!initLast && accessor.length === 1)
existingLength > 0
? base
: `(${base} = typeof ${base} === "undefined" ? {} : ${base})`;
let propsSoFar = accessor.slice(1, existingLength);
current += propertyAccess(propsSoFar);
if (existingLength >= accessor.length - 1) return current;
for (let i = Math.max(1, existingLength); i < accessor.length - 1; i++) {
// i is the current position in accessor that has been printed
let i = 1;
// all properties printed so far (excluding base)
let propsSoFar;
// if there is existingLength, print all properties until this position as property access
if (existingLength > i) {
propsSoFar = accessor.slice(1, existingLength);
i = existingLength;
current += propertyAccess(propsSoFar);
} else {
propsSoFar = [];
}
// all remainig properties (except the last one when initLast is not set)
// should be printed as initializer
const initUntil = initLast ? accessor.length : accessor.length - 1;
for (; i < initUntil; i++) {
const prop = accessor[i];
propsSoFar.push(prop);
current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess(
propsSoFar
)} || {})`;
}
return `${current}${propertyAccess([accessor[accessor.length - 1]])}`;
// print the last property as property access if not yet printed
if (i < accessor.length)
current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`;
return current;
};
/**