refactoring .toggle(..) (boosted by about 30%-40%)

Signed-off-by: Alex A. Naanou <alex.nanou@gmail.com>
This commit is contained in:
Alex A. Naanou 2018-12-30 02:12:12 +03:00
parent cbe97eba60
commit e58f6d2166

View File

@ -73,8 +73,8 @@ var util = require('lib/util')
// //
var normalizeSplit = function(args){ var normalizeSplit = function(args){
return (args.length == 1 && args[0] instanceof Array) ? return (args.length == 1 && args[0] instanceof Array) ?
args.pop() args.pop().slice()
: args } : args.slice() }
@ -1185,8 +1185,10 @@ var BaseTagsPrototype = {
toggle: function(tag, values, action){ toggle: function(tag, values, action){
var that = this var that = this
values = values instanceof Array ? values : [values] values = values instanceof Array ? values : [values]
// NOTE: this is cheating -- if tag is a list it will get
// stringified before the test...
var pattern = /\*/.test(tag) var pattern = /\*/.test(tag)
var ntag = this.normalize(tag) var ntag = this.normalize(tag instanceof Array ? tag : [tag])
// can't set pattern as tag... // can't set pattern as tag...
if(pattern && action == 'on'){ if(pattern && action == 'on'){
@ -1195,8 +1197,10 @@ var BaseTagsPrototype = {
return action == 'on' ? return action == 'on' ?
this.tag(tag, values) this.tag(tag, values)
: action == 'off' ? : action == 'off' ?
this.untag(tag, values) this.untag(tag, values)
: action == '?' ? : action == '?' ?
values values
.map(function(v){ .map(function(v){
@ -1204,16 +1208,33 @@ var BaseTagsPrototype = {
// non-strict pattern search... // non-strict pattern search...
that.tags(v, tag) that.tags(v, tag)
// strict test... // strict test...
: that.tags(v).indexOf(ntag) >= 0) ? 'on' : 'off' }) : new Set(that.tags(v)).intersect(ntag).size > 0) ? 'on' : 'off' })
// toggle each... // toggle each...
: values : values
.map(function(v){ // build the on/off lists...
return that.tags(v, tag) ? // XXX this will either set all the tags on (if at least
(that.untag(tag, v), 'off') // one is off) or off (if all are on) for each item...
// NOTE: we set only if we are not a pattern... .reduce(function(res, v){
: (!pattern ? var state = that.tags(v, tag)
(that.tag(tag, v), 'on')
: null) }) }, res.res.push(state ? 'off' : 'on')
state ?
res.untag.push(v)
: res.tag.push(v)
return res
}, {tag: [], untag: [], res: []})
// do the tagging...
.run(function(){
this.tag.length > 0
&& that.tag(tag, this.tag)
this.untag.length > 0
&& that.untag(tag, this.untag)
return this.res
}) },
// Replace tags... // Replace tags...
// //