import re, time

###################old implementation##################
_base_js_escapes = (
    ('\\', r'\x5C'),
    ('\'', r'\x27'),
    ('"', r'\x22'),
    ('>', r'\x3E'),
    ('<', r'\x3C'),
    ('&', r'\x26'),
    ('=', r'\x3D'),
    ('-', r'\x2D'),
    (';', r'\x3B')
)

# Escape every ASCII character with a value less than 32.
_js_escapes = (_base_js_escapes +
               tuple([('%c' % z, '\\x%02X' % z) for z in range(32)]))

def escapejs(value):
    for bad, good in _js_escapes:
        value = value.replace(bad, good)
    return value
#######################################################
    
#####################new implementation################
_js_escapes_dict = {
    '\\': r'\x5C',
    '\'': r'\x27',
    '"': r'\x22',
    '>': r'\x3E',
    '<': r'\x3C',
    '&': r'\x26',
    '=': r'\x3D',
    '-': r'\x2D',
    ';': r'\x3B',
    u'\u2028': r'\u2028',
    u'\u2029': r'\u2029',
}

# also escape every ASCII character with a value less than 32.
for z in range(32):
    _js_escapes_dict[chr(z)] = '\\x%02X' % z

# construct a Regex object matching the keys in _js_escapes_dict
_js_escapes_re = u''.join(sorted(_js_escapes_dict.keys()))
_js_escapes_re = re.sub(r'[\\\\\-\]]', r'\\\g<0>', _js_escapes_re) # escape \-]
_js_escapes_re = '[' + _js_escapes_re + ']'
_js_escapes_re = re.compile(_js_escapes_re)

def escapejs_new(value):
    """Hex encodes characters for use in JavaScript strings."""
    return _js_escapes_re.sub(lambda m: _js_escapes_dict[m.group(0)], value)
#######################################################

# time the functions
n = 100000
for test_string in (
    "x" * 5, "x" * 512, "'" * 5, "'" * 512,
    "Hello, I'm a simple string we're going to use. \\ - ; &",
):

    t_old = time.time()
    for x in range(n):
        escapejs(test_string)
    t_old = time.time() - t_old

    t_new = time.time()
    for x in range(n):
        escapejs_new(test_string)
    t_new = time.time() - t_new

    str = test_string 
    if len(str) > 10:
        str = str[:10] + "..."
    if t_new < t_old:
        print "%5.1fx speedup  %.1fs vs %.1fs %r" % (t_old / t_new, t_old, t_new, str)
    else:
        print "%5.1fx slowdown %.1fs vs %.1fs %r" % (t_new / t_old, t_old, t_new, str)

