javascript - efficiently limiting for...in loop to specific property keys -
i have function loop through nested objects contain precompiled regex patterns. checks each pattern against string, , if matches, replace using "abriv" value.
the code works notice when examining loop in debug mode both 'regex' , 'abriv' property being checked against string.
how optimize loop loop through 'regex' values when conducting second for...in? tried using accessors 'prop.regex' in loop doesnt seem work.
var car = /(\bauto\b|\bvehicle\b|\bride\b)/ig var bus = /(\bcoach\b)/ig var train = /(\bexpress\b|\brail\b)/ig var regexlist = { car: { abriv: 'car', regex: car }, bus: { abriv: 'bus', regex: bus }, train: { abriv: 'train', regex: train } } var teststring = "i drove auto"; function replacer(text) { (var regex in regexlist) { var obj = regexlist[regex]; (var prop in obj) { if (obj.regex.test(text) === true) { this.text = text.replace(obj.regex, obj.abriv); return this; } } } } replacer(teststring);
i think don't need second loop.
function replacer(text) { (var regex in regexlist) { var obj = regexlist[regex]; if (obj.regex.test(text) === true) { this.text = text.replace(obj.regex, obj.abriv); return this; } } }
is there missing here ?
Comments
Post a Comment