Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mythical-programmer/a5b4bbd3c57b17f85046 to your computer and use it in GitHub Desktop.
Save mythical-programmer/a5b4bbd3c57b17f85046 to your computer and use it in GitHub Desktop.
javascript: better completions autocompletes
{
"scope": "source.js - string, source.coffee, source.js.embedded.html",
// ## source
// * http://overapi.com/javascript/
// * http://www.w3schools.com/js/
"completions":
[
////////////////////////////////////////////////////////////////////////////////
////////////////////////////// start ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
["f ___", "function () {\n\t$1\n}"],
["e ___", "\\$($1)"],
["elem ___", "\\$($1)"],
["doc ___", "document"],
["this ___", "\\$(this)"],
["getElementById ___", "document.getElementById($1)"],
["getElementsByName ___", "document.getElementsByName($1)"],
["getElementsByTagName ___", "node.getElementsByTagName($1)"],
["setTimeout ___", "setTimeout(func$1, msec)"],
["setInterval ___", "setInterval(func$1, msec)"],
["inherit ___", "var newObj = object(oldObj);"], // prototypical inheritance; Object.prototype is end of the chain."],
["ready ___", "\\$(document).ready(function() {\n\t$1\n});"],
["cl ___", "console.log($1);"],
["console ___", "console.log($1);"],
//session
["sessionStorage.setItem ___", "sessionStorage.setItem('key$1', 'val');"],
["sessionStorage.getItem ___", "sessionStorage.getItem('$1')"],
["JSON.parse ___", "JSON.parse($1);"],
["JSON.stringify ___", "JSON.stringify($1)"],
//math
["Math.floor ___", "Math.floor($1)"],
["Math.random ___", "Math.random($1)"],
["math uniform random ___", "Math.floor(Math.random() * (hi-lo+1)) + lo$1; //uniform random number between lo(inclusive), hi(exclusive)"],
//mixed
["stack trace ___", "console.log((new Error()).stack + ' :: $1');"],
[".each function ___", ".each(function(i, element){\n\t$1\n});"],
["func ___", "var ${1:functionName} = function ($2) {\n\t$3\n};"],
["parseInt ___douglas", "parseInt('42',10$1)"],
["try_catch ___", "try{\n\t$1\n} catch(e){\n\t\n}"],
["prompt ___", "prompt('question$1','input_value')"],
["switch ___", "switch($1) {\ncase 1:\n\t\tbreak;\n\tdefault: break;\n}"],
["case ___", "case '$1':\n\t$1\n\tbreak;"],
["constructor ___douglas", "var MyClass$1 = function () {\n\t// This is the constructor\n\tthis.member=initialize; \n\treturn this; //optional; instead of returning undefined, just return this;\n}\n//methods are shared by new objects through prototype, memory efficient\nMyClass.prototype = {\n\t// Add methods to the newly defined 'class'\n\tfirstMethod: function() { },\n\tsecondMethod: function() { }\n};\nvar obj = new MyClass();//returns a link to MyClass.prototype"],
["for_in ___douglas", "for(_variable in _object) {\n\tif (object.hasOwnProperty(_variable)) {\n\t_statements\n}\n}"],
["object ___douglas", "function object(o) {\n\tfunction F() {}\t// constructor function\n\tF.prototype = o;\t// prototype\n\treturn new F();\t\t// new operator; use all three to make prototype operator\n}\nvar newObj = object(oldObj);"],
["singleton ___douglas", "var singleton = {\n\tfirstMethod: function () { },\n\tsecondMethod: function() { }\n};"],
["singleton1 ___douglas", "//this is a really basic pattern; Applications are singletons; YAHOO(use yours) to avoid global namespace\nYAHOO.MyPropertyApp = function() {\n\tvar privateVar;\n\tfunction privateFunction() { }\n\t// privileged methods have access to private var, private methods through closure (not using 'this'); direct binding\n\treturn {\n\t\tfirstMethod: function() {\n\t\t\t//can use privateVar here\n\t\t},\n\t\tsecondMethod: function() {\n\t\t\t//can use privateVar here\n\t\t}\n\t};\t// due to closure, these functions are also accessible even after the outer function returns\n}();\t// note: it is not function, but value after evaluating the function"],
["power_constructor ___douglas", "/** template for power constructor */\nfunction powerConstructor() {\n\tvar that = object(oldObject); // 'this' not used to avoid reserved word problem\n\tvar privateVariable;\t// private variables using 'var' inside function\n\t// inner functions are private functions/methods\n\tfunction privateFunction(x) {}\n\t// privileged methods (that...)\n\tthat.firstMethod = function (a,b) {\n\t\t// access private variable\n\t};\n\tthat.secondMethod = function (c) {\n\t\t// access private variable\n\t};\n\treturn that;\n}\nmyObject = powerConstructor();\t// no need to use 'new'"],
["parasitic_inheritance ___douglas", "/** parasitic inheritance; better than the pseudoclassical pattern; (using MyClass.prototype= something... and all); Douglas used to this pattern to write a javascript compiler */\nfunction gizmo(id) {\n\treturn {\n\t\tid: id,\t// remove this statement and id will be private by closure; and private var is shared through the chain of parasitic construction\n\t\ttoString: function () {\n\t\t\treturn 'gizmo' + id;\n\t\t}\n\t};\n}\nfunction hoozit(id) {\n\tvar that = gizmo(id);\t// 1. let the previous constructor do all the work\n\t// 2. augment 'that' and then 3. return 'that'\n\tthat.test = function (testid) {\n\t\treturn testid === this.id;\n\t};\n\treturn that;\n}"],
["package_scope_shared_secrets ___douglas", "/** package scope may not be particularly useful; useful for people coming from classical model to code using that */\nfunction gizmo(id, secret) {\n\tsecret = secret || {};\n\tsecret.id = id;\n\treturn {\n\t\ttoString: function () {\n\t\t\treturn 'gizmo' + secret.id;\n\t\t}\n\t};\n}\nfunction hoozit(id) {\n\tvar secret = {};\t// final; further inheritance will not be able to pass secrets\n\tvar that = gizmo(id, secret);\t// to share the private info across multiple classes (package scope) \n\tthat.test = function (testid) {\n\t\treturn testid === secret.id;\n\t};\n\treturn that;\n}"],
["later ___douglas", "/** augment to Object.prototype; now all objects can understand later method */\nObject.prototype.later = \n\tfunction(msec, method) {\n\t\tvar that = this,\t// inner functions do not have access to 'this' of the caller (design error)\n\t\t\targs = Array.prototype.slice.apply(arguments, [2]);\t// need to do this; another design error in js; arguments doesnt have Array functions. it is an array like object with a length member (not fixed); maybe fixed in 4th edition; (chop off 1st two args)\n\t\tif (typeof method === 'string') {\n\t\t\tmethod = that[method];\n\t\t}\n\t\tsetTimeout(function () {\n\t\t\tmethod.apply(that, args);\t// method.apply invokes the method with the given arguments\n\t\t}, msec);\n\t\treturn that;\n\t};\nmyObj.later(1000, 'earse_function', true);"],
["multiples_mouseover ___douglas", "// need weird indirection, but caused everything to work\nfor (in in ..) {\n\tvar div_id = divs[i].id;\n\tdivs[i].mouseover = function (id) {\n\t\t// do not directly call show_element_id() on this line; instead do the return function () {}; due to closure, binding is to current value that can change over time;\n\t\treturn function () {\n\t\t\tshow_element_id(id);\n\t\t};\n\t}(div_id);\n}"],
//string
["charAt ___", "str$1.charAt(7$2)"],
["concat ___", "str$1.concat('$1 ',' ')"],
["indexOf ___", "str$1.indexOf('substr$2')!=-1$3"],
["indexOf2 ___", "_arr$1.indexOf('a$2',2$3) // start searching for 'a' after 2 locations"],
["lastIndexOf ___", "str$1.lastIndexOf('r$2')"],
["fromCharCode ___", "String.fromCharCode(97$1,98,99,120,121,122)"],
["match ___", "str$1.match(regexStr$2)"],
["replace ___", "str$1.replace(/_regex$2/gi, 'jQuery')"],
["search ___", "str$1.search(_regex$2). If you require a regular expression, use search(). Otherwise, indexOf() is going to be faster."],
["slice ___", "str$1.slice(0$2,4)"],
["split ___", "str$1.split('substr$2')"],
["sub ___", "str$1.substring(0$2,4)"],
["lower ___", "str$1.toLowerCase()"],
["upper ___", "str$1.toUpperCase()"],
["trim ___douglas", "//developer forgot to write a trim function to String type; So what we can write one\nString.prototype.trim = function () {\n\treturn this.replace(/^\\s*(\\S*(\\s+\\S)*)\\s*$/,'$1');\n}"],
["supplant ___douglas", "//supplant() does variable substitution on the string. It scans through the string looking for expressions enclosed in { } braces. If an expression is found, use it as a key on the object, and if the key has a string value or number value, it is substituted for the bracket expression and it repeats. This is useful for automatically fixing URLs.\nif (!String.prototype.supplant) {\n\tString.prototype.supplant = function (o) {\n\t\treturn this.replace(\n\t\t\t/\\{([^{}]*)\\}/g,\n\t\t\tfunction (a, b) {\n\t\t\t\tvar r = o[b];\n\t\t\t\treturn typeof r === 'string' || typeof r === 'number' ? r : a;\n\t\t\t}\n\t\t);\n\t};\n}\nvar param = {domain: 'valvion.com', media: 'http://media.valvion.com/'};\nvar url = '{media}logo.gif'.supplant(param);\nconsole.log(url.supplant(param));"],
["entityify ___", "/** entityify() produces a string in which '<', '>', and '&' are replaced with their HTML entity equivalents. This is essential for placing arbitrary strings into HTML texts. */\nif (!String.prototype.entityify) {\n\tString.prototype.entityify = function () {\n\t\treturn this.replace(/&/g, '&amp;').replace(/</g,\n\t\t\t'&lt;').replace(/>/g, '&gt;');\n\t};\n}"],
["quote ___", "/** quote() produces a quoted string. This method returns a string that is like the original string except that it is wrapped in quotes and all quote and backslash characters are preceded with backslash. */\nif (!String.prototype.quote) {\n\tString.prototype.quote = function () {\n\t\tvar c, i, l = this.length, o = ''';\n\t\tfor (i = 0; i < l; i += 1) {\n\t\t\tc = this.charAt(i);\n\t\t\tif (c >= ' ') {\n\t\t\t\tif (c === '\\\\' || c === ''') {\n\t\t\t\t\to += '\\\\';\n\t\t\t\t}\n\t\t\t\to += c;\n\t\t\t} else {\n\t\t\t\tswitch (c) {\n\t\t\t\tcase '\\b':\n\t\t\t\t\to += '\\\b';\n\t\t\t\t\tbreak;\n\t\t\t\tcase '\\f':\n\t\t\t\t\to += '\\\f';\n\t\t\t\t\tbreak;\n\t\t\t\tcase '\\n':\n\t\t\t\t\to += '\\\n';\n\t\t\t\t\tbreak;\n\t\t\t\tcase '\\r':\n\t\t\t\t\to += '\\\r';\n\t\t\t\t\tbreak;\n\t\t\t\tcase '\\t':\n\t\t\t\t\to += '\\\t';\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tc = c.charCodeAt();\n\t\t\t\t\to += '\\u00' + Math.floor(c / 16).toString(16) +\n\t\t\t\t\t\t(c % 16).toString(16);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn o + ''';\n\t};\n}"],
["isEmpty ___", "\n/** isEmpty(v) returns true if v is an object containing no enumerable members. */\nfunction isEmpty(o) {\n\tvar i, v;\n\tif (typeOf(o) === 'object') {\n\t\tfor (i in o) {\n\t\t\tv = o[i];\n\t\t\tif (v !== undefined && typeOf(v) !== 'function') {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}"],
["typeOf ___", "/** fixed typeOf taking care of 'array' type and 'null' type; default typeOf method shows 'array' (not helpful) and 'null' as object(a mistake in language) */\nfunction typeOf(value) {\n\tvar s = typeof value;\n\tif (s === 'object') {\n\t\tif (value) {\n\t\t\tif (Object.prototype.toString.call(value) == '[object Array]') {\n\t\t\t\ts = 'array';\n\t\t\t}\n\t\t} else {\n\t\t\ts = 'null';\n\t\t}\n\t}\n\treturn s;\n}"],
["push ___", "push($1)"],
["forEach ___", "arr.forEach(function(el, idx, ar) {\n\tconsole.log(el);\n});"],
["map ___", "arr.map(function(el, idx, ar) {\n\treturn el*el;\t\t// perform map on each element\n});"],
["filter ___", "arr.filter(function(el, idx, ar) {\n\treturn el>2;\t// filter condition\n});"],
["filter_inbuilt ___", "arr.filter(Boolean$1); // can pass inbuilt functions also; return all truthy values"],
["some ___", "arr.some(function(el, idx, ar) {\n\treturn el>2;\t// whether atleast one element satisfies this\n});"],
["every ___", "arr.every(function(el, idx, ar) {\n\treturn el>2;\t// whether every element satisfies this\n});"],
["reduce ___", "arr.reduce(function (res, el, idx, arr) {\n\treturn res * el;\n}, 1);"],
["reduce_actual_len ___", "[1,,,3].reduce(function (len, el) {\n\treturn len+1;\n}, 0);"],
["arguments_push ___", "args=Array.prototype.slice.call(arguments);\nargs.push();"],
["filter_for_string ___", "[].filter(str, function (el, idx) {\n\treturn idx>7;\t// returns array with elements as chars\n});"],
["unshift ___", "arr.unshift(_'insert_to_front$1');"],
// events
["onclick for dynamically added elems ___", "\\$(document$1).on('click', '.item', function(){\n\t$1\n});"],
["dblclick ___", "\\$($1).dblclick(function(){\n\t$1\n});"],
["click ___", "\\$($1).click(function($2){\n\t$3\n});$4"],
["animate ___", "\\$($1).animate({top:'+=10px'},500)"],
["effect_explode ___", "\\$($1).effect('explode$1')"],
["effect_bounce ___", "\\$(this$1).effect('bounce', {times:2}, 900)"],
// jquery UI
["accordion ___", "\\$('div_id$1').accordion({collapsible: true, active: false})"],
["draggable ___", "\\$($1).draggable()"],
["resizable ___", "\\$($1).resizable()"],
["selectable ___", "\\$($1).selectable()"],
["sortable ___", "\\$($1).sortable()"],
["ajax ___", "$.ajax({\n\turl: '/api/getWeather$1',\n\tdata: {\n\t\t'zipcode': 97201\n\t},\n\tsuccess: function( data ) {\n\t\t\\$( '#weather-temp' ).html( '<strong>' + data + '</strong> degrees' );\n\t}\n});"],
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// end /////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment