Created
March 14, 2011 15:57
-
-
Save mooz/869363 to your computer and use it in GitHub Desktop.
generate ac source for underscore.js from document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (doc) { | |
let helps = {}; | |
function recordDoc(k, doc) helps[k] = doc; | |
function chomp(s) s.replace(/^[ \t\n\r]+/, "").replace(/[ \t\n\r]+$/, ""); | |
function esc(s) s.replace(/(?!\\)"/g, '\\"'); | |
function quote(s) '"' + s + '"'; | |
Array.forEach(doc.querySelectorAll("#documentation > p[id]"), function (_p) { | |
let p = _p.cloneNode(true); | |
let headName = p.removeChild(p.querySelector("b.header")).textContent; | |
let aliases = let (cand = p.querySelector("span.alias")) ( | |
cand ? p.removeChild(cand).querySelector("b") | |
.textContent.split(/,[ ]*/) | |
: [] | |
); | |
let names = [headName].concat(aliases); | |
let helpLines = chomp(p.textContent) | |
.split("\n") | |
.map(chomp) | |
.filter(function (l) l.length) | |
.map(esc); | |
let helpTitle = helpLines.shift(); | |
let helpBody = helpLines.join("\n"); | |
function getProperHelpTitle(name) helpTitle | |
.replace(/(_\.)(?:[a-zA-Z_$][a-zA-Z_$0-9]*)(.*)/, "$1" + name + "$2"); | |
names.forEach(function (name) { | |
helps[name] = getProperHelpTitle(name) + "\n\n" + helpBody; | |
}); | |
}); | |
return ["(" + quote(name) + " . " + quote(help) + ")" | |
for ([name, help] in Iterator(helps))].join("\n"); | |
})(document); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(add-hook 'js2-mode-hook | |
(lambda () | |
(define-key js2-mode-map (kbd ".") 'js2usj-insert-dot))) | |
;; ============================================================ ;; | |
;; Settings for eldoc | |
;; ============================================================ ;; | |
(defun underscore-js-turn-on-eldoc-mode () | |
"Enable underscore-js-eldoc-mode" | |
(interactive) | |
(set (make-local-variable 'eldoc-documentation-function) | |
'underscore-js-print-function-signature) | |
(turn-on-eldoc-mode)) | |
(defun underscore-js-print-function-signature () | |
"Returns documentation string for the current symbol." | |
(when | |
(save-excursion | |
(re-search-backward | |
"\\(?:^\\|[^a-zA-Z_$]\\)\\([a-zA-Z_$][a-zA-Z0-9_$]*\\)[ ]*(" | |
(point-min) t)) | |
(let* ((pair | |
(assoc (match-string 1) ac-underscore-js-doc-alist)) | |
(doc (and pair | |
(nth 0 (split-string (cdr pair) "\n"))))) | |
(when doc | |
(eldoc-message doc))))) | |
;; ============================================================ ;; | |
(defsubst js2usj-dotted-node-p (node) | |
(and node | |
(or (js2-prop-get-node-p node) | |
(js2-call-node-p node)))) | |
(defsubst js2usj-get-dotted-node-left (node) | |
(cond | |
((js2-prop-get-node-p node) | |
(js2-prop-get-node-left node)) | |
((js2-call-node-p node) | |
(js2-call-node-target node)))) | |
(defun js2usj-get-leftmost-name-node () | |
(let ((node (js2-node-at-point))) | |
(when (and (js2-name-node-p node) | |
(js2usj-dotted-node-p (js2-name-node-parent node))) | |
(setq node (js2-name-node-parent node))) | |
(while (js2usj-dotted-node-p node) | |
(setq node (js2usj-get-dotted-node-left node))) | |
(and (js2-name-node-p node) node))) | |
(defun js2usj-insert-dot () | |
(interactive) | |
(let ((leftmost (save-excursion | |
(search-backward-regexp "[^ \t\n\r]" (point-min) t) | |
(js2usj-get-leftmost-name-node)))) | |
(insert ".") | |
(when (and leftmost | |
(equal (js2-name-node-name leftmost) "_")) | |
(auto-complete '(ac-source-underscore-js))))) | |
(defvar ac-source-underscore-js | |
'((cache) | |
(prefix "\\.\\(\\(?:[a-zA-Z_$][a-zA-Z0-9_$]*\\)?\\)" nil 1) | |
(candidates . (lambda () | |
(loop for (name . doc) in ac-underscore-js-doc-alist | |
collect name))) | |
(document . (lambda (sym) | |
(cdr (assoc sym ac-underscore-js-doc-alist)))) | |
(requires . 0))) | |
(defvar ac-underscore-js-doc-alist | |
'(("each" . "_.each(list, iterator, [context]) | |
Iterates over a list of elements, yielding each in turn to an iterator | |
function. The iterator is bound to the context object, if one is | |
passed. Each invocation of iterator is called with three arguments: | |
\(element, index, list). If list is a JavaScript object, iterator's | |
arguments will be (value, key, list). Delegates to the native | |
forEach function if it exists.") | |
("forEach" . "_.forEach(list, iterator, [context]) | |
Iterates over a list of elements, yielding each in turn to an iterator | |
function. The iterator is bound to the context object, if one is | |
passed. Each invocation of iterator is called with three arguments: | |
\(element, index, list). If list is a JavaScript object, iterator's | |
arguments will be (value, key, list). Delegates to the native | |
forEach function if it exists.") | |
("map" . "_.map(list, iterator, [context]) | |
Produces a new array of values by mapping each value in list | |
through a transformation function (iterator). If the native map method | |
exists, it will be used instead. If list is a JavaScript object, | |
iterator's arguments will be (value, key, list).") | |
("reduce" . "_.reduce(list, iterator, memo, [context]) | |
Also known as inject and foldl, reduce boils down a | |
list of values into a single value. Memo is the initial state | |
of the reduction, and each successive step of it should be returned by | |
iterator.") | |
("inject" . "_.inject(list, iterator, memo, [context]) | |
Also known as inject and foldl, reduce boils down a | |
list of values into a single value. Memo is the initial state | |
of the reduction, and each successive step of it should be returned by | |
iterator.") | |
("foldl" . "_.foldl(list, iterator, memo, [context]) | |
Also known as inject and foldl, reduce boils down a | |
list of values into a single value. Memo is the initial state | |
of the reduction, and each successive step of it should be returned by | |
iterator.") | |
("reduceRight" . "_.reduceRight(list, iterator, memo, [context]) | |
The right-associative version of reduce. Delegates to the | |
JavaScript 1.8 version of reduceRight, if it exists. Foldr | |
is not as useful in JavaScript as it would be in a language with lazy | |
evaluation.") | |
("foldr" . "_.foldr(list, iterator, memo, [context]) | |
The right-associative version of reduce. Delegates to the | |
JavaScript 1.8 version of reduceRight, if it exists. Foldr | |
is not as useful in JavaScript as it would be in a language with lazy | |
evaluation.") | |
("detect" . "_.detect(list, iterator, [context]) | |
Looks through each value in the list, returning the first one that | |
passes a truth test (iterator). The function returns as | |
soon as it finds an acceptable element, and doesn't traverse the | |
entire list.") | |
("select" . "_.select(list, iterator, [context]) | |
Looks through each value in the list, returning an array of all | |
the values that pass a truth test (iterator). Delegates to the | |
native filter method, if it exists.") | |
("filter" . "_.filter(list, iterator, [context]) | |
Looks through each value in the list, returning an array of all | |
the values that pass a truth test (iterator). Delegates to the | |
native filter method, if it exists.") | |
("reject" . "_.reject(list, iterator, [context]) | |
Returns the values in list without the elements that the truth | |
test (iterator) passes. The opposite of select.") | |
("all" . "_.all(list, [iterator], [context]) | |
Returns true if all of the values in the list pass the iterator | |
truth test. If an iterator is not provided, the truthy value of | |
the element will be used instead. Delegates to the native method every, if | |
present.") | |
("every" . "_.every(list, [iterator], [context]) | |
Returns true if all of the values in the list pass the iterator | |
truth test. If an iterator is not provided, the truthy value of | |
the element will be used instead. Delegates to the native method every, if | |
present.") | |
("any" . "_.any(list, [iterator], [context]) | |
Returns true if any of the values in the list pass the | |
iterator truth test. Short-circuits and stops traversing the list | |
if a true element is found. Delegates to the native method some, | |
if present.") | |
("some" . "_.some(list, [iterator], [context]) | |
Returns true if any of the values in the list pass the | |
iterator truth test. Short-circuits and stops traversing the list | |
if a true element is found. Delegates to the native method some, | |
if present.") | |
("include" . "_.include(list, value) | |
Returns true if the value is present in the list, using | |
=== to test equality. Uses indexOf internally, if list | |
is an Array.") | |
("contains" . "_.contains(list, value) | |
Returns true if the value is present in the list, using | |
=== to test equality. Uses indexOf internally, if list | |
is an Array.") | |
("invoke" . "_.invoke(list, methodName, [*arguments]) | |
Calls the method named by methodName on each value in the list. | |
Any extra arguments passed to invoke will be forwarded on to the | |
method invocation.") | |
("pluck" . "_.pluck(list, propertyName) | |
An convenient version of what is perhaps the most common use-case for | |
map: extracting a list of property values.") | |
("max" . "_.max(list, [iterator], [context]) | |
Returns the maximum value in list. If iterator is passed, | |
it will be used on each value to generate the criterion by which the | |
value is ranked.") | |
("min" . "_.min(list, [iterator], [context]) | |
Returns the minimum value in list. If iterator is passed, | |
it will be used on each value to generate the criterion by which the | |
value is ranked.") | |
("sortBy" . "_.sortBy(list, iterator, [context]) | |
Returns a sorted list, ranked by the results of running each | |
value through iterator.") | |
("sortedIndex" . "_.sortedIndex(list, value, [iterator]) | |
Uses a binary search to determine the index at which the value | |
should be inserted into the list in order to maintain the list's | |
sorted order. If an iterator is passed, it will be used to compute | |
the sort ranking of each value.") | |
("toArray" . "_.toArray(list) | |
Converts the list (anything that can be iterated over), into a | |
real Array. Useful for transmuting the arguments object.") | |
("size" . "_.size(list) | |
Return the number of values in the list.") | |
("first" . "_.first(array, [n]) | |
Returns the first element of an array. Passing n will | |
return the first n elements of the array.") | |
("head" . "_.head(array, [n]) | |
Returns the first element of an array. Passing n will | |
return the first n elements of the array.") | |
("rest" . "_.rest(array, [index]) | |
Returns the rest of the elements in an array. Pass an index | |
to return the values of the array from that index onward.") | |
("tail" . "_.tail(array, [index]) | |
Returns the rest of the elements in an array. Pass an index | |
to return the values of the array from that index onward.") | |
("last" . "_.last(array) | |
Returns the last element of an array.") | |
("compact" . "_.compact(array) | |
Returns a copy of the array with all falsy values removed. | |
In JavaScript, false, null, 0, \"\", | |
undefined and NaN are all falsy.") | |
("flatten" . "_.flatten(array) | |
Flattens a nested array (the nesting can be to any depth).") | |
("without" . "_.without(array, [*values]) | |
Returns a copy of the array with all instances of the values | |
removed. === is used for the equality test.") | |
("uniq" . "_.uniq(array, [isSorted]) | |
Produces a duplicate-free version of the array, using === to test | |
object equality. If you know in advance that the array is sorted, | |
passing true for isSorted will run a much faster algorithm.") | |
("unique" . "_.unique(array, [isSorted]) | |
Produces a duplicate-free version of the array, using === to test | |
object equality. If you know in advance that the array is sorted, | |
passing true for isSorted will run a much faster algorithm.") | |
("intersect" . "_.intersect(*arrays) | |
Computes the list of values that are the intersection of all the arrays. | |
Each value in the result is present in each of the arrays.") | |
("zip" . "_.zip(*arrays) | |
Merges together the values of each of the arrays with the | |
values at the corresponding position. Useful when you have separate | |
data sources that are coordinated through matching array indexes.") | |
("indexOf" . "_.indexOf(array, value, [isSorted]) | |
Returns the index at which value can be found in the array, | |
or -1 if value is not present in the array. Uses the native | |
indexOf function unless it's missing. If you're working with a | |
large array, and you know that the array is already sorted, pass true | |
for isSorted to use a faster binary search.") | |
("lastIndexOf" . "_.lastIndexOf(array, value) | |
Returns the index of the last occurrence of value in the array, | |
or -1 if value is not present. Uses the native lastIndexOf | |
function if possible.") | |
("range" . "_.range([start], stop, [step]) | |
A function to create flexibly-numbered lists of integers, handy for | |
each and map loops. start, if omitted, defaults | |
to 0; step defaults to 1. Returns a list of integers | |
from start to stop, incremented (or decremented) by step, | |
exclusive.") | |
("bind" . "_.bind(function, object, [*arguments]) | |
Bind a function to an object, meaning that whenever | |
the function is called, the value of this will be the object. | |
Optionally, bind arguments to the function to pre-fill them, | |
also known as currying.") | |
("bindAll" . "_.bindAll(object, [*methodNames]) | |
Binds a number of methods on the object, specified by | |
methodNames, to be run in the context of that object whenever they | |
are invoked. Very handy for binding functions that are going to be used | |
as event handlers, which would otherwise be invoked with a fairly useless | |
this. If no methodNames are provided, all of the object's | |
function properties will be bound to it.") | |
("memoize" . "_.memoize(function, [hashFunction]) | |
Memoizes a given function by caching the computed result. Useful | |
for speeding up slow-running computations. If passed an optional | |
hashFunction, it will be used to compute the hash key for storing | |
the result, based on the arguments to the original function.") | |
("delay" . "_.delay(function, wait, [*arguments]) | |
Much like setTimeout, invokes function after wait | |
milliseconds. If you pass the optional arguments, they will be | |
forwarded on to the function when it is invoked.") | |
("defer" . "_.defer(function) | |
Defers invoking the function until the current call stack has cleared, | |
similar to using setTimeout with a delay of 0. Useful for performing | |
expensive computations or HTML rendering in chunks without blocking the UI thread | |
from updating.") | |
("throttle" . "_.throttle(function, wait) | |
Returns a throttled version of the function, that, when invoked repeatedly, | |
will only actually call the wrapped function at most once per every wait | |
milliseconds. Useful for rate-limiting events that occur faster than you | |
can keep up with.") | |
("debounce" . "_.debounce(function, wait) | |
Repeated calls to a debounced function will postpone it's execution | |
until after wait milliseconds have elapsed. Useful for implementing | |
behavior that should only happen after the input has stopped arriving. | |
For example: rendering a preview of a Markdown comment, recalculating a | |
layout after the window has stopped being resized...") | |
("wrap" . "_.wrap(function, wrapper) | |
Wraps the first function inside of the wrapper function, | |
passing it as the first argument. This allows the wrapper to | |
execute code before and after the function runs, adjust the arguments, | |
and execute it conditionally.") | |
("compose" . "_.compose(*functions) | |
Returns the composition of a list of functions, where each function | |
consumes the return value of the function that follows. In math terms, | |
composing the functions f(), g(), and h() produces | |
f(g(h())).") | |
("keys" . "_.keys(object) | |
Retrieve all the names of the object's properties.") | |
("values" . "_.values(object) | |
Return all of the values of the object's properties.") | |
("functions" . "_.functions(object) | |
Returns a sorted list of the names of every method in an object — | |
that is to say, the name of every function property of the object.") | |
("methods" . "_.methods(object) | |
Returns a sorted list of the names of every method in an object — | |
that is to say, the name of every function property of the object.") | |
("extend" . "_.extend(destination, *sources) | |
Copy all of the properties in the source objects over to the | |
destination object. It's in-order, to the last source will override | |
properties of the same name in previous arguments.") | |
("clone" . "_.clone(object) | |
Create a shallow-copied clone of the object. Any nested objects | |
or arrays will be copied by reference, not duplicated.") | |
("tap" . "_.tap(object, interceptor) | |
Invokes interceptor with the object, and then returns object. | |
The primary purpose of this method is to \"tap into\" a method chain, in order to perform operations on intermediate results within the chain.") | |
("isEqual" . "_.isEqual(object, other) | |
Performs an optimized deep comparison between the two objects, to determine | |
if they should be considered equal.") | |
("isEmpty" . "_.isEmpty(object) | |
Returns true if object contains no values.") | |
("isElement" . "_.isElement(object) | |
Returns true if object is a DOM element.") | |
("isArray" . "_.isArray(object) | |
Returns true if object is an Array.") | |
("isArguments" . "_.isArguments(object) | |
Returns true if object is an Arguments object.") | |
("isFunction" . "_.isFunction(object) | |
Returns true if object is a Function.") | |
("isString" . "_.isString(object) | |
Returns true if object is a String.") | |
("isNumber" . "_.isNumber(object) | |
Returns true if object is a Number.") | |
("isBoolean" . "_.isBoolean(object) | |
Returns true if object is either true or false.") | |
("isDate" . "_.isDate(object) | |
Returns true if object is a Date.") | |
("isRegExp" . "_.isRegExp(object) | |
Returns true if object is a RegExp.") | |
("isNaN" . "_.isNaN(object) | |
Returns true if object is NaN. Note: this is not | |
the same as the native isNaN function, which will also return | |
true if the variable is undefined.") | |
("isNull" . "_.isNull(object) | |
Returns true if the value of object is null.") | |
("isUndefined" . "_.isUndefined(variable) | |
Returns true if variable is undefined.") | |
("noConflict" . "_.noConflict() | |
Give control of the \"_\" variable back to its previous owner. Returns | |
a reference to the Underscore object.") | |
("identity" . "_.identity(value) | |
Returns the same value that is used as the argument. In math: | |
f(x) = x | |
This function looks useless, but is used throughout Underscore as | |
a default iterator.") | |
("times" . "_.times(n, iterator) | |
Invokes the given iterator function n times.") | |
("mixin" . "_.mixin(object) | |
Allows you to extend Underscore with your own utility functions. Pass | |
a hash of {name: function} definitions to have your functions | |
added to the Underscore object, as well as the OOP wrapper.") | |
("uniqueId" . "_.uniqueId([prefix]) | |
Generate a globally-unique id for client-side models or DOM elements | |
that need one. If prefix is passed, the id will be appended to it.") | |
("template" . "_.template(templateString, [context]) | |
Compiles JavaScript templates into functions that can be evaluated | |
for rendering. Useful for rendering complicated bits of HTML from JSON | |
data sources. Template functions can both interpolate variables, using | |
<%= … %>, as well as execute arbitrary JavaScript code, with | |
<% … %>. When you evaluate a template function, pass in a | |
context object that has properties corresponding to the template's free | |
variables. If you're writing a one-off, you can pass the context | |
object as the second parameter to template in order to render | |
immediately instead of returning a template function.") | |
("chain" . "_(obj).chain() | |
Returns a wrapped object. Calling methods on this object will continue | |
to return wrapped objects until value is used. ( | |
A more realistic example.)") | |
("value" . "_(obj).value() | |
Extracts the value of a wrapped object."))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment