From 2ef642fdeb705e2334b1d740698b7ca13575d26c Mon Sep 17 00:00:00 2001 From: rolux Date: Wed, 4 Jan 2012 13:12:48 +0530 Subject: [PATCH] misc updates to ox.js --- source/Ox.UI/js/Form/Ox.ArrayEditable.js | 2 +- source/Ox/js/Collection.js | 59 ++++++++++++++++-------- source/Ox/js/DOM.js | 2 +- source/Ox/js/Encoding.js | 52 +++++++++++---------- source/Ox/js/Format.js | 6 +-- source/Ox/js/Geo.js | 19 ++++---- source/Ox/js/JavaScript.js | 9 ++-- source/Ox/js/Math.js | 30 +++++++----- source/Ox/js/Object.js | 22 +++++---- source/Ox/js/Request.js | 11 ++++- source/Ox/js/String.js | 17 +++---- 11 files changed, 136 insertions(+), 93 deletions(-) diff --git a/source/Ox.UI/js/Form/Ox.ArrayEditable.js b/source/Ox.UI/js/Form/Ox.ArrayEditable.js index 3d67728e..05d706b7 100644 --- a/source/Ox.UI/js/Form/Ox.ArrayEditable.js +++ b/source/Ox.UI/js/Form/Ox.ArrayEditable.js @@ -8,7 +8,7 @@ Ox.ArrayEditable = function(options, self) { self = self || {}; var that = Ox.Element(options.editable === false ? {} : { - tooltip: 'Doubleclick to add ' + (options.itemName : 'item') + tooltip: 'Doubleclick to add ' + (options.itemName || 'item') }) .defaults({ editable: true, diff --git a/source/Ox/js/Collection.js b/source/Ox/js/Collection.js index 4a208393..9a8c4ed8 100644 --- a/source/Ox/js/Collection.js +++ b/source/Ox/js/Collection.js @@ -188,16 +188,19 @@ Ox.forEach = function(col, fn, includePrototype) { }; /*@ -Ox.getObjectById Returns an array element with a given id - > Ox.getObjectById([{id: "foo", title: "Foo"}, {id: "bar", title: "Bar"}], "foo") - {id: "foo", title: "Foo"} +Ox.getIndex Returns the first array index of an object where obj[key] is val + > Ox.getIndex([{a: 1}, {a: 2}, {a: 1}], 'a', 2) + 1 + > Ox.getIndex([{a: 1}, {a: 2}, {a: 1}], 'a', 1) + 0 + > Ox.getIndex([{a: 1}, {a: 2}, {a: 1}], 'a', 0) + -1 @*/ -// fixme: should this be getElementById() ? -Ox.getObjectById = function(arr, id) { - var ret = null; - Ox.forEach(arr, function(v) { - if (v.id == id) { - ret = v; +Ox.getIndex = function(arr, key, val) { + var ret = -1; + Ox.forEach(arr, function(obj, ind) { + if (obj[key] === val) { + ret = ind; return false; } }); @@ -205,23 +208,43 @@ Ox.getObjectById = function(arr, id) { }; /*@ -Ox.getPositionById Returns the index of an array element with a given id - > Ox.getPositionById([{id: "foo", title: "Foo"}, {id: "bar", title: "Bar"}], "foo") +Ox.getIndexById Returns the first array index of an object with a given id + > Ox.getIndexById([{id: 'foo', str: 'Foo'}, {id: 'bar', str: 'Bar'}], 'foo') 0 @*/ -// fixme: this should be getIndexById() -Ox.getPositionById = function(arr, id) { - var ret = -1; - Ox.forEach(arr, function(v, i) { - if (v.id == id) { - ret = i; +// FIXME: this should be getIndexById() only +Ox.getIndexById = Ox.getPositionById = function(arr, id) { + return Ox.getIndex(arr, 'id', id); +}; + +/*@ +Ox.getObject Returns the first object in an array where obj[key] is val + > Ox.getObject([{a: 1, i: 0}, {a: 2, i: 1}, {a: 1, i: 2}], 'a', 2) + {a: 2, i: 1} + > Ox.getObject([{a: 1, i: 0}, {a: 2, i: 1}, {a: 1, i: 2}], 'a', 1) + {a: 1, i: 0} + > Ox.getObject([{a: 1, i: 0}, {a: 2, i: 1}, {a: 1, i: 2}], 'a', 0) + null +@*/ +Ox.getObject = function(arr, key, val) { + var ret = null; + Ox.forEach(arr, function(obj) { + if (obj[key] === val) { + ret = obj; return false; } }); return ret; }; -// fixme: and what about getElementBy() and getIndexBy() ? +/*@ +Ox.getObjectById Returns the first object in an array with a given id + > Ox.getObjectById([{id: 'foo', str: 'Foo'}, {id: 'bar', str: 'Bar'}], 'foo') + {id: "foo", str: "Foo"} +@*/ +Ox.getObjectById = function(arr, id) { + return Ox.getObject(arr, 'id', id); +}; /*@ Ox.getset Generic getter and setter function diff --git a/source/Ox/js/DOM.js b/source/Ox/js/DOM.js index 91380a7c..d5468d00 100644 --- a/source/Ox/js/DOM.js +++ b/source/Ox/js/DOM.js @@ -2,6 +2,7 @@ /*@ Ox.canvas Generic canvas object + # Description -------------------------------------------------------------- Returns an object with the properties: canvas, context, data and imageData. # Usage -------------------------------------------------------------------- @@ -14,7 +15,6 @@ Ox.canvas Generic canvas object @*/ Ox.canvas = function() { - // Ox.print("CANVAS", arguments) var c = {}, isImage = arguments.length == 1, image = isImage ? arguments[0] : { width: arguments[0], height: arguments[1] diff --git a/source/Ox/js/Encoding.js b/source/Ox/js/Encoding.js index 42cec791..6f085641 100644 --- a/source/Ox/js/Encoding.js +++ b/source/Ox/js/Encoding.js @@ -433,12 +433,12 @@ if (code < 128) { str = chr; } else if (code < 2048) { - str = String.fromCharCode(code >> 6 | 192) + - String.fromCharCode(code & 63 | 128); + str = String.fromCharCode(code >> 6 | 192) + + String.fromCharCode(code & 63 | 128); } else { - str = String.fromCharCode(code >> 12 | 224) + - String.fromCharCode(code >> 6 & 63 | 128) + - String.fromCharCode(code & 63 | 128); + str = String.fromCharCode(code >> 12 | 224) + + String.fromCharCode(code >> 6 & 63 | 128) + + String.fromCharCode(code & 63 | 128); } return str; }).join(''); @@ -455,40 +455,44 @@ '¥€$' @*/ Ox.decodeUTF8 = function(str) { - var bytes = Ox.map(str, function(v) { - return v.charCodeAt(0); - }), + var code, i = 0, len = str.length, - str = ''; + ret = ''; while (i < len) { - if (bytes[i] <= 128) { - str += String.fromCharCode(bytes[i]); + code = Ox.range(3).map(function(o) { + return str.charCodeAt(i + o); + }); + if (code[0] <= 128) { + ret += str[i]; i++; } else if ( - bytes[i] >= 192 && bytes[i] < 240 && - i < len - (bytes[i] < 224 ? 1 : 2) + code[0] >= 192 && code[0] < 240 + && i < len - (code[0] < 224 ? 1 : 2) ) { - if (bytes[i + 1] >= 128 && bytes[i + 1] < 192) { - if (bytes[i] < 224) { - str += String.fromCharCode((bytes[i] & 31) << 6 | - bytes[i + 1] & 63); + if (code[1] >= 128 && code[1] < 192) { + if (code[0] < 224) { + ret += String.fromCharCode( + (code[0] & 31) << 6 | code[1] & 63 + ); i += 2; - } else if (bytes[i + 2] >= 128 && bytes[i + 2] < 192) { - str += String.fromCharCode((bytes[i] & 15) << 12 | - (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63); + } else if (code[2] >= 128 && code[2] < 192) { + ret += String.fromCharCode( + (code[0] & 15) << 12 | (code[1] & 63) << 6 + | code[2] & 63 + ); i += 3; } else { - throwUTF8Error(bytes[i + 2], i + 2); + throwUTF8Error(code[2], i + 2); } } else { - throwUTF8Error(bytes[i + 1], i + 1); + throwUTF8Error(code[1], i + 1); } } else { - throwUTF8Error(bytes[i], i); + throwUTF8Error(code[0], i); } } - return str; + return ret; }; })(); \ No newline at end of file diff --git a/source/Ox/js/Format.js b/source/Ox/js/Format.js index ea1e8fe8..67bf9dec 100644 --- a/source/Ox/js/Format.js +++ b/source/Ox/js/Format.js @@ -350,10 +350,8 @@ Ox.formatDateRangeDuration = function(start, end, utc) { } else { // outside the range, rewind the date by one unit Ox['set' + parts[i]](date, Ox['get' + parts[i]](date, utc) - 1, utc); - if (key == 'month') { - // and revert to original day - Ox.setDate(date, day, utc); - } + // and revert to original day + key == 'month' && Ox.setDate(date, day, utc); break; } } diff --git a/source/Ox/js/Geo.js b/source/Ox/js/Geo.js index 1ae36f8d..30a7439d 100644 --- a/source/Ox/js/Geo.js +++ b/source/Ox/js/Geo.js @@ -29,16 +29,15 @@ @*/ Ox.getArea = function(pointA, pointB) { /* - area of a ring between two latitudes: - 2 * PI * r^2 * abs(sin(lat0) - sin(lat1)) - see http://mathforum.org/library/drmath/view/63767.html - */ - /* - 2 * Math.PI * - Math.pow(Ox.EARTH_RADIUS, 2) * - Math.abs(Math.sin(Ox.rad(0)) - Math.sin(Ox.rad(1))) * - Math.abs(Ox.rad(0) - Ox.rad(1)) / - (2 * Math.PI) + area of a ring between two latitudes: + 2 * PI * r^2 * abs(sin(latA) - sin(latB)) + see http://mathforum.org/library/drmath/view/63767.html + => + 2 * Math.PI + * Math.pow(Ox.EARTH_RADIUS, 2) + * Math.abs(Math.sin(Ox.rad(latA)) - Math.sin(Ox.rad(latB))) + * Math.abs(Ox.rad(lngA) - Ox.rad(lngB)) + / (2 * Math.PI) */ if (Ox.crossesDateline(pointA, pointB)) { pointB.lng += 360; diff --git a/source/Ox/js/JavaScript.js b/source/Ox/js/JavaScript.js index fd392c67..e365f9b5 100644 --- a/source/Ox/js/JavaScript.js +++ b/source/Ox/js/JavaScript.js @@ -722,8 +722,9 @@ Ox.tokenize = (function() { // scan back to the previous significant token, // or the beginning of the source while ( - typeof tokens[--index] != 'undefined' - && ['comment', 'linebreak', 'whitespace'].indexOf(tokens[index].type) > -1 + tokens[--index] !== void 0 && [ + 'comment', 'linebreak', 'whitespace' + ].indexOf(tokens[index].type) > -1 ) { offset += tokens[index].length; } @@ -732,7 +733,9 @@ Ox.tokenize = (function() { isRegExp = true; } else { prevToken = tokens[index]; - prevString = source.substr(cursor - prevToken.length - offset, prevToken.length); + prevString = source.substr( + cursor - prevToken.length - offset, prevToken.length + ); isRegExp = ( prevToken.type == 'keyword' && ['false', 'null', 'true'].indexOf(prevString) == -1 diff --git a/source/Ox/js/Math.js b/source/Ox/js/Math.js index 186bd287..6c8b7c17 100644 --- a/source/Ox/js/Math.js +++ b/source/Ox/js/Math.js @@ -2,7 +2,7 @@ /*@ Ox.asinh Inverse hyperbolic sine - Strangely missing from Math. + Missing from Math. @*/ Ox.asinh = function(x) { // fixme: no test @@ -11,7 +11,7 @@ Ox.asinh = function(x) { /*@ Ox.deg Takes radians, returns degrees - Strangely missing from Math. + Missing from Math. > Ox.deg(2 * Math.PI) 360 @*/ @@ -55,18 +55,20 @@ Ox.limit Limits a number by a given mininum and maximum 3 > Ox.limit(2, 1) 1 + > Ox.limit(-1, -2) + -2 @*/ Ox.limit = function(/*num[[, min], max]*/) { var len = arguments.length, num = arguments[0], - min = len == 3 ? arguments[1] : 0, // fixme: should be -Infinity + min = len == 3 ? arguments[1] : -Infinity, max = arguments[len - 1]; return Math.min(Math.max(num, min), max); }; /*@ Ox.log Returns the logarithm of a given number to a given base - Strangely missing from Math. + Missing from Math. > Ox.log(100, 10) 2 > Ox.log(Math.E) @@ -86,13 +88,12 @@ Ox.mod Modulo function 9 @*/ Ox.mod = function(num, by) { - var mod = num % by; - return mod >= 0 ? mod : mod + by; + return (num % by + by) % by; }; /*@ Ox.rad Takes degrees, returns radians - Strangely missing from Math. + Missing from Math. > Ox.rad(360) 2 * Math.PI @*/ @@ -101,7 +102,12 @@ Ox.rad = function(deg) { }; /*@ -Ox.random Returns a random integer +Ox.random Returns a random integer within a given range + () -> 0 or 1 + (max) -> Integer between 0 (inclusive) and max (exclusive) + (min, max) -> Integer between min (inclusive) and max (exclusive) + > [0, 1].indexOf(Ox.random()) > -1 + true > [0, 1, 2].indexOf(Ox.random(3)) > -1 true > Ox.random(1, 2) == 1 @@ -109,9 +115,9 @@ Ox.random Returns a random integer @*/ Ox.random = function() { var len = arguments.length, - min = len == 1 ? 0 : arguments[0], - max = arguments[len - 1]; - return min + parseInt(Math.random() * (max - min)); + min = len == 2 ? arguments[0] : 0, + max = len ? arguments[len - 1] : 2; + return min + Math.floor(Math.random() * (max - min)); }; /*@ @@ -130,7 +136,7 @@ Ox.round = function(num, dec) { /*@ Ox.sinh Hyperbolic sine - Strangely missing from Math. + Missing from Math. @*/ Ox.sinh = function(x) { // fixme: no test diff --git a/source/Ox/js/Object.js b/source/Ox/js/Object.js index 155c1d5a..c83b6ce7 100644 --- a/source/Ox/js/Object.js +++ b/source/Ox/js/Object.js @@ -5,7 +5,6 @@ Ox.extend Extends an object with one or more other objects > Ox.extend({a: 1, b: 1, c: 1}, {b: 2, c: 2}, {c: 3}) {a: 1, b: 2, c: 3} @*/ - Ox.extend = function() { var obj = arguments[0]; Ox.forEach(Array.prototype.slice.call(arguments, 1), function(arg, i) { @@ -17,9 +16,10 @@ Ox.extend = function() { }; /*@ -Ox.keyOf undocumented +Ox.keyOf Equivalent of [].indexOf for objects + > Ox.keyOf({a: 1, b: 2, c: 3}, 1) + 'a' @*/ - Ox.keyOf = function(obj, val) { var key; Ox.forEach(obj, function(v, k) { @@ -40,7 +40,6 @@ Ox.serialize Parses an object into query parameters > Ox.serialize({string: 'foo', empty: {}, null: null, undefined: void 0}) 'string=foo' @*/ - Ox.serialize = function(obj) { var arr = []; Ox.forEach(obj, function(val, key) { @@ -57,18 +56,21 @@ Ox.unserialize Parses query parameters into an object {a: '1', b: '2', c: '3'} > Ox.unserialize('a=-1&b=2.3&c=4,5', true) {a: -1, b: 2.3, c: [4, 5]} + > Ox.unserialize('a=1&b=&c&a=0', true) + {a: 0} @*/ - Ox.unserialize = function(str, toNumber) { var obj = {}; Ox.forEach(str.split('&'), function(val) { if (val) { var arr = val.split('='); - obj[arr[0]] = !toNumber ? arr[1] - : arr[1].indexOf(',') == -1 ? +arr[1] - : arr[1].split(',').map(function(val) { - return +val; - }); + if (arr[1]) { + obj[arr[0]] = !toNumber ? arr[1] + : arr[1].indexOf(',') == -1 ? +arr[1] + : arr[1].split(',').map(function(val) { + return +val; + }); + } } }); return obj; diff --git a/source/Ox/js/Request.js b/source/Ox/js/Request.js index e66bde15..404c6a03 100644 --- a/source/Ox/js/Request.js +++ b/source/Ox/js/Request.js @@ -31,7 +31,7 @@ Ox.getJSON Get and parse a remote JSON file (url, callback) -> undefined url Remote URL callback Callback function - data The contents of the remote resource + data The parsed contents of the remote resource @*/ Ox.getJSON = function(url, callback) { Ox.get(url, function(data) { @@ -39,6 +39,14 @@ Ox.getJSON = function(url, callback) { }); }; +/*@ +Ox.getJSONC Get and parse a remote JSONC file + JSONC is JSON with JavaScript line or block comments + (url, callback) -> undefined + url Remote URL + callback Callback function + data The parsed contents of the remote resource +@*/ Ox.getJSONC = function(url, callback) { Ox.get(url, function(data) { callback(JSON.parse(Ox.minify(data))); @@ -53,7 +61,6 @@ Ox.loadFile Loads a file (image, script or stylesheet) file Local path or remote URL callback Callback function @*/ - Ox.loadFile = (function() { // fixme: this doesn't handle errors yet // fixme: rename to getFile? diff --git a/source/Ox/js/String.js b/source/Ox/js/String.js index 5a068f94..0fdb1e02 100644 --- a/source/Ox/js/String.js +++ b/source/Ox/js/String.js @@ -37,12 +37,12 @@ Ox.clean = function(str) { /*@ Ox.endsWith Checks if a string ends with a given substring If the substring is a string literal (and not a variable), - /sub$/.test(str) or !!/sub$/(str) + /sub$/.test(str) or !!/sub$/.exec(str) is shorter than Ox.ends(str, sub). > Ox.endsWith('foobar', 'bar') true @*/ -Ox.endsWith = function(str, sub) { +Ox.ends = Ox.endsWith = function(str, sub) { // fixme: rename to ends return str.substr(str.length - sub.length) == sub; }; @@ -248,23 +248,24 @@ Ox.repeat = function(val, num) { return ret; }; +/*@ +Ox.reverse Reverses a string + > Ox.reverse('foobar') + 'raboof' +@*/ Ox.reverse = function(str) { - /* - Ox.reverse("foo") - oof - */ return str.toString().split('').reverse().join(''); }; /*@ Ox.startsWith Checks if a string starts with a given substring If the substring is a string literal (and not a variable), - /^sub/.test(str) or !!/^sub/(str) + /^sub/.test(str) or !!/^sub/.exec(str) is shorter than Ox.starts(str, sub). > Ox.startsWith('foobar', 'foo') true @*/ -Ox.startsWith = function(str, sub) { +Ox.starts = Ox.startsWith = function(str, sub) { // fixme: rename to starts return str.substr(0, sub.length) == sub; };