Skip to content

Commit

Permalink
perf(index): Create a copy only for specified keys
Browse files Browse the repository at this point in the history
  • Loading branch information
mrmlnc authored and michael-ciniawsky committed Nov 19, 2016
1 parent ba9d706 commit 5239bc0
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ function walk (opts, nodes) {
const keys = loopParams.keys

// creates a copy of the keys that will be changed within the loop
const localsBackup = makeBackupLoopKeys(keys[0], keys[1], opts.locals)
const localsBackup = makeLocalsBackup(keys, opts.locals)

// run the loop, different types of loops for arrays and objects
if (Array.isArray(target)) {
Expand All @@ -195,7 +195,7 @@ function walk (opts, nodes) {
}

// returns the original keys values that was changed within the loop
opts.locals = revertBackupedLocals(keys[0], keys[1], opts.locals, localsBackup)
opts.locals = revertBackupedLocals(keys, opts.locals, localsBackup)

// return directly out of the loop, which will skip the "each" tag
return m
Expand Down Expand Up @@ -269,27 +269,31 @@ function parseLoopStatement (input) {
}

/**
* Creates a backup of keys within the loop
* Creates a backup of keys values
*/
function makeBackupLoopKeys (p1, p2, locals) {
function makeLocalsBackup (keys, locals) {
let backup = {}
if (p1 && data.locals.hasOwnProperty(p1)) backup[p1] = data.locals[p1]
if (p2 && data.locals.hasOwnProperty(p2)) backup[p2] = data.locals[p2]

for (let i = 0; i < keys.length; i++) {
const key = keys[i]
if (data.locals.hasOwnProperty(key)) backup[key] = cloneDeep(data.locals[key])
}

return backup
}

/**
* Returns the original keys values
*/
function revertBackupedLocals (p1, p2, locals, backup) {
// Remove loop keys from locals
delete locals[p1]
delete locals[p2]

// Revert copied keys
if (p1 && backup.hasOwnProperty(p1)) locals[p1] = backup[p1]
if (p2 && backup.hasOwnProperty(p2)) locals[p2] = backup[p2]
function revertBackupedLocals (keys, locals, backup) {
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
// remove key from locals
delete locals[key]

// revert copied key value
if (backup.hasOwnProperty(key)) locals[key] = backup[key]
}

return locals
}
Expand Down

0 comments on commit 5239bc0

Please sign in to comment.