Commit 3fc0c515 authored by S Anand's avatar S Anand

ENH: G.url.update() accepts key-specific mode parameter

For example, if the URL is ?a=1&b=1 and we want to update it with
?a=2&b=3, updating 'a' but toggling 'b', then we can specify
mode='b=toggle'. This will only toggle 'b', not 'a', and result in the
URL ?a=2&b=1&b=3
parent ad288f4e
This diff is collapsed.
......@@ -177,14 +177,29 @@ _url_update = function(args, mode) {
search_key = self[_url_parse_qname[0]],
search_list = self[_url_parse_qname[1]],
qparts = [],
modes = {},
key, val, i, l, hash, search_list_key, result
if (mode) {
// Ensure that mode is a string
mode = '' + mode
// If the mode is like a=add&b=toggle, treat it like URL search params and
// convert it into a dictionary
if (mode.match(/[&=]/))
modes = _url_parse('?' + mode).searchKey
// If the mode is just a string like add, del, toggle, apply it to all keys
else
for (key in args)
modes[key] = mode
}
for (key in args) {
val = args[key]
if (val === null) {
search_list[key] = []
} else {
if (!_is_array(val)) val = [val]
if (!mode)
if (!modes[key])
search_list[key] = val
else {
// Ensure that search_list[key] exists
......@@ -195,7 +210,7 @@ _url_update = function(args, mode) {
hash[val[i].toString()] = 1
// Ensure that mode is a string
mode = '' + mode
mode = '' + modes[key]
if (mode.match(/add/i))
search_list[key] = search_list[key].concat(val)
......
......@@ -317,6 +317,14 @@ describe('url.update', function() {
assert_update('/?a=1&b=2', G.url.parse('?x=8').searchKey, '/?a=1&b=2&x=8', {msg: 1})
})
it('accepts composite mode parameter', function() {
assert_update('/?a=1&b=2&c=3', G.url.parse('?a=1&b=2&b=3&c=6&d=7').searchList, '/?b=3&c=3&c=6&d=7', {mode: 'a=del&b=toggle&c=add&d=toggle', msg: 1})
assert_update('/?a=1&b=2', G.url.parse('?a=2&b=1&b=2&c=3&d=4').searchList, '/?a=2&b=1&c=3', {mode: 'b=toggle&c=toggle&d=del', msg: 2})
assert_update('/', G.url.parse('?a=1&b=1').searchKey, '/?a=1&b=1', {mode: 'b=toggle', msg: 2})
assert_update('/?a=1&b=1', G.url.parse('?a=1&b=2').searchKey, '/?a=1&b=1&b=2', {mode: 'b=toggle', msg: 2})
assert_update('/?a=1&b=1&b=2', G.url.parse('?a=1&b=1').searchKey, '/?a=1&b=2', {mode: 'b=toggle', msg: 2})
})
it('removes search parameters', function() {
assert_update('/?a=1&b=2', {a:null}, '/?b=2', {msg: 1})
assert_update('/?a=1&b=2', {a:null, b:null}, '/', {msg: 2})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment