Updates to Underscore definitions & tests

This commit is contained in:
Boris Yankov 2012-10-08 02:36:30 +03:00
parent 9f369bc856
commit ee07aeb4d6
2 changed files with 270 additions and 254 deletions

View File

@ -1,9 +1,8 @@
// Type definitions for Underscore 1.4.1
// https://github.com/borisyankov/DefinitelyTyped
interface KeyValuePair {
key: string;
value: any;
interface UnderscoreWrappedObject {
value () : any;
}
interface TemplateSettings {
@ -12,40 +11,59 @@ interface TemplateSettings {
escape?: RegExp;
}
interface ListIterator {
(value, key, list?): void;
}
interface ObjectIterator {
(element, index, list?): void;
}
interface UnderscoreStatic {
/****
Collections
*****/
each(list: any[], iterator: any, context?: any): any[]; // interface Iterator = (element, index, list) => any;
each(obj: any, iterator: any, context?: any): any[]; // (value, key, list)
forEach(list: any[], iterator: any, context?: any): any[];
forEach(obj: any, iterator: any, context?: any): any[];
each(list: any[], iterator: ListIterator, context?: any): any[];
each(object: any, iterator: ObjectIterator, context?: any): any[];
forEach(list: any[], iterator: ObjectIterator, context?: any): any[];
forEach(object: any, iterator: ListIterator, context?: any): any[];
map(list: any[], iterator: any, context?: any): any[];
map(obj: any, iterator: any, context?: any): any[];
collect(list: any[], iterator: any, context?: any): any[];
collect(obj: any, iterator: any, context?: any): any[];
map(list: any[], iterator: ListIterator, context?: any): any[];
map(object: any, iterator: ObjectIterator, context?: any): any[];
collect(list: any[], iterator: ListIterator, context?: any): any[];
collect(object: any, iterator: ObjectIterator, context?: any): any[];
reduce(list: any[], iterator: any, memo: any, context?: any): any[];
reduce(list: any[], iterator: any, memo: any, context?: any): any[]; // TODO iterator
inject(list: any[], iterator: any, memo: any, context?: any): any[];
foldl(list: any[], iterator: any, memo: any, context?: any): any[];
reduceRight(list: any[], iterator: any, memo: any, context?: any): any[];
foldr(list: any[], iterator: any, memo: any, context?: any): any[];
find(list: any[], iterator: any, context?: any): any;
detect(list: any[], iterator: any, context?: any): any;
filter(list: any[], iterator: any, context?: any): any[];
select(list: any[], iterator: any, context?: any): any[];
where(list: any[], properties: any): any[];
reject(list: any[], iterator: any, context?: any): any[];
all(list: any[], iterator: any, context?: any): bool;
_any(list: any[], iterator?: any, context?: any): bool;
every(list: any[], iterator: any, context?: any): bool;
any(list: any[], iterator?: any, context?: any): bool;
some(list: any[], iterator?: any, context?: any): bool;
contains(list: any, value: any): bool;
contains(list: any[], value: any): bool;
include(list: any, value: any): bool;
include(list: any[], value: any): bool;
invoke(list: any[], methodName: string, arguments: any[]): any;
invoke(obj: any, methodName: string, ...arguments: any[]): any;
invoke(object: any, methodName: string, ...arguments: any[]): any;
pluck(list: any[], propertyName: string): string[];
max(list: any[], iterator?: any, context?: any): any;
@ -63,18 +81,25 @@ interface UnderscoreStatic {
first(array: any[], n?: number): any;
head(array: any[], n?: number): any;
take(array: any[], n?: number): any;
initial(array: any[], n?: number): any[];
last(array: any[], n?: number): any;
rest(array: any[], n?: number): any[];
tail(array: any[], n?: number): any[];
drop(array: any[], n?: number): any[];
compact(array: any[]): any[];
flatten(array: any[], shallow?: bool): any[];
without(array: any[], ...values: any[]): any[];
union(...arrays: any[]): any[];
intersection(...arrays: any[]): any[];
difference(array: any[], ...others: any[]): any[];
union(...arrays: any[][]): any[];
intersection(...arrays: any[][]): any[];
difference(array: any[], ...others: any[][]): any[];
uniq(array: any[], isSorted?: bool, iterator?: any): any[];
unique(array: any[], isSorted?: bool, iterator?: any): any[];
zip(...arrays: any[]): any[];
object(list: any[], values: any[]): any;
indexOf(array: any[], value: any, isSorted?: bool): number;
@ -86,8 +111,8 @@ interface UnderscoreStatic {
/****
Functions
*****/
bind(func: any, context: any, ...arguments: any[]): () => any;
bindAll(obj: any, ...methodNames: string[]): any;
bind(func: (...as : any[]) => any, context: any, ...arguments: any[]): () => any;
bindAll(object: any, ...methodNames: string[]): any;
memoize(func: any, hashFunction?: any): any;
defer(func: () => any);
delay(func: any, wait: number, ...arguments: any[]): any;
@ -96,7 +121,7 @@ interface UnderscoreStatic {
debounce(func: any, wait: number, immediate?: bool): any;
once(func: any): any;
after(count: number, func: any): any;
wrap(func: any, wrapper: any): () => any;
wrap(func: (...as : any[]) => any, wrapper: any): () => any;
compose(...functions: any[]): any;
/****
@ -104,17 +129,18 @@ interface UnderscoreStatic {
*****/
keys(object: any): any[];
values(object: any): any[];
pairs(object: any): KeyValuePair[];
invert(object: any): any[];
pairs(object: any): any[];
invert(object: any): any;
functions(object: any): string[];
methods(object: any): string[];
extend(destination: any, sources: any): any;
extend(destination: any, ...sources: any[]): any;
pick(object: any, ...keys: string[]): any;
omit(object: any, key: string): any;
omit(object: any, keys: string[]): any;
defaults(object: any, defaults: any): any;
omit(object: any, ...keys: string[]): any;
defaults(object: any, ...defaults: any[]): any;
clone(object: any): any;
tap(object: any, interceptor: any): any;
tap(object: any, interceptor: (...as : any[]) => any): any;
has(object: any, key: string): bool;
isEqual(object: any, other: any): bool;
isEmpty(object: any): bool;
@ -136,23 +162,22 @@ interface UnderscoreStatic {
/****
Utility
*****/
noConflict(): UnderscoreStatic;
noConflict(): any;
identity(value: any): any;
times(n: number, iterator: any, context?: any): any[];
times(n: number, iterator: (index : number) => void, context?: any): void;
random(min: number, max: number): number;
mixin(object: any): any;
mixin(object: any): void;
uniqueId(prefix: string): string;
uniqueId(): number;
escape(string: string): string;
result(object: any, property: any): any;
escape(str: string): string;
result(object: any, property: string): any;
templateSettings: TemplateSettings;
template(templateString: string, data?: any, settings?: any): (data: any) => string;
template(templateString: string, data?: any, settings?: any): (...data: any[]) => string;
/****
Chaining
*****/
chain(obj: any): any;
// (obj).value()
chain(object: any): UnderscoreWrappedObject;
}
declare var _: UnderscoreStatic;

View File

@ -1,249 +1,240 @@
/// <reference path="../Definitions/underscore.d.ts" />
declare var $: any;
declare var $;
function alert(thing: any) {
$('#content').append('<div>' + thing + '</div>');
}
_.each([1, 2, 3], (num) => alert(num));
_.each({ one: 1, two: 2, three: 3 }, (num, key) => alert(num));
$(() => {
_.map([1, 2, 3], (num) => num * 3);
_.map({ one: 1, two: 2, three: 3 }, (num, key) => num * 3);
_.each([1, 2, 3], (num) => alert(num));
_.each({ one: 1, two: 2, three: 3 }, (num, key) => alert(num));
var sum = _.reduce([1, 2, 3], (memo, num) => memo + num, 0);
_.map([1, 2, 3], (num) => num * 3);
_.map({ one: 1, two: 2, three: 3 }, (num, key) => num * 3);
var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, (a, b) => a.concat(b), []);
var sum = _.reduce([1, 2, 3], (memo, num) => memo + num, 0);
// alert(sum);
var even = _.find([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0);
var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, (a, b) => a.concat(b), []);
// alert(flat);
var evens = _.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0);
var even = _.find([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0);
var listOfPlays = [{ title: "Cymbeline", author: "Shakespeare", year: 1611 }, { title: "The Tempest", author: "Shakespeare", year: 1611 }, { title: "Other", author: "Not Shakespeare", year: 2012 }];
_.where(listOfPlays, { author: "Shakespeare", year: 1611 });
var evens = _.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0);
var odds = _.reject([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0);
var listOfPlays = [{ title: "Cymbeline", author: "Shakespeare", year: 1611 }, { title: "The Tempest", author: "Shakespeare", year: 1611 }, { title: "Other", author: "Not Shakespeare", year: 2012 }];
_.where(listOfPlays, { author: "Shakespeare", year: 1611 });
_.all([true, 1, null, 'yes'], _.identity);
var odds = _.reject([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0);
_.any([null, 0, 'yes', false]);
_.all([true, 1, null, 'yes'], _.identity);
_.contains([1, 2, 3], 3);
_._any([null, 0, 'yes', false]);
_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
_.contains([1, 2, 3], 3);
var stooges = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }];
_.pluck(stooges, 'name');
_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
_.max(stooges, (stooge) => stooge.age);
var stooges = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }];
_.pluck(stooges, 'name');
var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
var stooges = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }];
_.max(stooges, (stooge) => stooge.age);
_.sortBy([1, 2, 3, 4, 5, 6], (num) => Math.sin(num));
var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
_.groupBy([1.3, 2.1, 2.4], (num) => Math.floor(num));
_.groupBy(['one', 'two', 'three'], 'length');
_.sortBy([1, 2, 3, 4, 5, 6], (num) => Math.sin(num));
_.countBy([1, 2, 3, 4, 5], (num) => num % 2 == 0 ? 'even' : 'odd');
_.groupBy([1.3, 2.1, 2.4], (num) => Math.floor(num));
_.groupBy(['one', 'two', 'three'], 'length');
_.shuffle([1, 2, 3, 4, 5, 6]);
_.countBy([1, 2, 3, 4, 5], (num) => num % 2 == 0 ? 'even' : 'odd');
// (function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
_.shuffle([1, 2, 3, 4, 5, 6]);
_.size({ one: 1, two: 2, three: 3 });
//(function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
///////////////////////////////////////////////////////////////////////////////////////
_.size({ one: 1, two: 2, three: 3 });
_.first([5, 4, 3, 2, 1]);
_.initial([5, 4, 3, 2, 1]);
_.last([5, 4, 3, 2, 1]);
_.rest([5, 4, 3, 2, 1]);
_.compact([0, 1, false, 2, '', 3]);
_.flatten([1, [2], [3, [[4]]]]);
_.flatten([1, [2], [3, [[4]]]], true);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
_.uniq([1, 2, 1, 3, 1, 4]);
_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
_.object([['moe', 30], ['larry', 40], ['curly', 50]]);
_.indexOf([1, 2, 3], 2);
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
_.sortedIndex([10, 20, 30, 40, 50], 35);
_.range(10);
_.range(1, 11);
_.range(0, 30, 5);
_.range(0, 30, 5);
_.range(0);
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
_.first([5, 4, 3, 2, 1]);
_.initial([5, 4, 3, 2, 1]);
_.last([5, 4, 3, 2, 1]);
_.rest([5, 4, 3, 2, 1]);
_.compact([0, 1, false, 2, '', 3]);
//_.flatten([1, [2], [3, [[4]]]]);
//_.flatten([1, [2], [3, [[4]]]], true);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
_.uniq([1, 2, 1, 3, 1, 4]);
_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
// _.object([['moe', 30], ['larry', 40], ['curly', 50]]);
_.indexOf([1, 2, 3], 2);
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
_.sortedIndex([10, 20, 30, 40, 50], 35);
_.range(10);
_.range(1, 11);
_.range(0, 30, 5);
_.range(0, 30, 5);
_.range(0);
var func = function (greeting) { return greeting + ': ' + this.name };
func = _.bind(func, { name: 'moe' }, 'hi');
func();
///////////////////////////////////////////////////////////////////////////////////////
var buttonView = {
label: 'underscore',
onClick: function () { alert('clicked: ' + this.label); },
onHover: function () { console.log('hovering: ' + this.label); }
};
_.bindAll(buttonView);
$('#underscore_button').bind('click', buttonView.onClick);
var func = function (greeting) { return greeting + ': ' + this.name };
func = _.bind(func, { name: 'moe' }, 'hi');
// func();
var buttonView = {
label: 'underscore',
onClick: function () { alert('clicked: ' + this.label); },
onHover: function () { console.log('hovering: ' + this.label); }
};
_.bindAll(buttonView);
//$('#underscore_button').bind('click', buttonView.onClick);
var fibonacci = _.memoize(function (n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
_.defer(function () { alert('deferred'); });
var updatePosition = () => alert('updating position...');
var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);
var calculateLayout = () => alert('calculating layout...');
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
var createApplication = () => alert('creating application...');
var initialize = _.once(createApplication);
initialize();
initialize();
var notes: any[];
var render = () => alert("rendering...");
var renderNotes = _.after(notes.length, render);
_.each(notes, (note) => note.asyncSave({ success: renderNotes }));
var hello = function (name) { return "hello: " + name; };
hello = _.wrap(hello, (func) => { return "before, " + func("moe") + ", after"; });
// hello();
var greet = function (name) { return "hi: " + name; };
var exclaim = function (statement) { return statement + "!"; };
var welcome = _.compose(exclaim, greet);
welcome('moe');
///////////////////////////////////////////////////////////////////////////////////////
_.keys({ one: 1, two: 2, three: 3 });
_.values({ one: 1, two: 2, three: 3 });
_.pairs({ one: 1, two: 2, three: 3 });
_.invert({ Moe: "Moses", Larry: "Louis", Curly: "Jerome" });
_.functions(_);
_.extend({ name: 'moe' }, { age: 50 });
_.pick({ name: 'moe', age: 50, userid: 'moe1' }, 'name', 'age');
_.omit({ name: 'moe', age: 50, userid: 'moe1' }, 'userid');
var iceCream = { flavor: "chocolate" };
_.defaults(iceCream, { flavor: "vanilla", sprinkles: "lots" });
_.clone({ name: 'moe' });
_.chain([1, 2, 3, 200])
.filter(function (num) { return num % 2 == 0; })
.tap(alert)
.map(function (num) { return num * num })
.value();
_.has({ a: 1, b: 2, c: 3 }, "b");
var moe = { name: 'moe', luckyNumbers: [13, 27, 34] };
var clone = { name: 'moe', luckyNumbers: [13, 27, 34] };
moe == clone;
_.isEqual(moe, clone);
_.isEmpty([1, 2, 3]);
_.isEmpty({});
_.isElement($('body')[0]);
(function () { return _.isArray(arguments); })();
_.isArray([1, 2, 3]);
_.isObject({});
_.isObject(1);
// (() => { return _.isArguments(arguments); })(1, 2, 3);
_.isArguments([1, 2, 3]);
_.isFunction(alert);
_.isString("moe");
_.isNumber(8.4 * 5);
_.isFinite(-101);
_.isFinite(-Infinity);
_.isBoolean(null);
_.isDate(new Date());
_.isRegExp(/moe/);
_.isNaN(NaN);
isNaN(undefined);
_.isNaN(undefined);
_.isNull(null);
_.isNull(undefined);
// _.isUndefined(window.missingVariable);
///////////////////////////////////////////////////////////////////////////////////////
var underscore = _.noConflict();
var moe2 = { name: 'moe' };
moe2 === _.identity(moe);
// _(3).times(function(n){ genie.grantWishNumber(n); });
_.random(0, 100);
_.mixin({
capitalize: function (string) {
return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
}
});
// _("fabio").capitalize();
_.uniqueId('contact_');
_.escape('Curly, Larry & Moe');
var object = { cheese: 'crumpets', stuff: function () { return 'nonsense'; } };
_.result(object, 'cheese');
_.result(object, 'stuff');
var compiled = _.template("hello: <%= name %>");
compiled({ name: 'moe' });
var list2 = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
_.template(list2, { people: ['moe', 'curly', 'larry'] });
var template = _.template("<b><%- value %></b>");
template({ value: '<script>' });
var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({ epithet: "stooge" });
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
};
var template = _.template("Hello {{ name }}!");
template({ name: "Mustache" });
_.template("Using 'with': <%= data.answer %>", { answer: 'no' }, { variable: 'data' });
var fibonacci = _.memoize(function (n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
_.defer(function () { alert('deferred'); });
var updatePosition = () => alert('updating position...');
var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);
var calculateLayout = () => alert('calculating layout...');
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
var createApplication = () => alert('creating application...');
var initialize = _.once(createApplication);
initialize();
initialize();
var notes: any[];
var render = () => alert("rendering...");
var renderNotes = _.after(notes.length, render);
_.each(notes, (note) => note.asyncSave({ success: renderNotes }));
var hello = function (name) { return "hello: " + name; };
hello = _.wrap(hello, (func) => { return "before, " + func("moe") + ", after"; });
hello();
var greet = function (name) { return "hi: " + name; };
var exclaim = function (statement) { return statement + "!"; };
var welcome = _.compose(exclaim, greet);
welcome('moe');
///////////////////////////////////////////////////////////////////////////////////////
_.keys({ one: 1, two: 2, three: 3 });
_.values({ one: 1, two: 2, three: 3 });
_.pairs({ one: 1, two: 2, three: 3 });
_.invert({ Moe: "Moses", Larry: "Louis", Curly: "Jerome" });
_.functions(_);
_.extend({ name: 'moe' }, { age: 50 });
_.pick({ name: 'moe', age: 50, userid: 'moe1' }, 'name', 'age');
_.omit({ name: 'moe', age: 50, userid: 'moe1' }, 'userid');
var iceCream = { flavor: "chocolate" };
_.defaults(iceCream, { flavor: "vanilla", sprinkles: "lots" });
_.clone({ name: 'moe' });
_.chain([1, 2, 3, 200])
.filter(function (num) { return num % 2 == 0; })
.tap(alert)
.map(function (num) { return num * num })
.value();
_.has({ a: 1, b: 2, c: 3 }, "b");
var moe = { name: 'moe', luckyNumbers: [13, 27, 34] };
var clone = { name: 'moe', luckyNumbers: [13, 27, 34] };
moe == clone;
_.isEqual(moe, clone);
_.isEmpty([1, 2, 3]);
_.isEmpty({});
_.isElement($('body')[0]);
(function () { return _.isArray(arguments); })();
_.isArray([1, 2, 3]);
_.isObject({});
_.isObject(1);
// (() => { return _.isArguments(arguments); })(1, 2, 3);
_.isArguments([1, 2, 3]);
_.isFunction(alert);
_.isString("moe");
_.isNumber(8.4 * 5);
_.isFinite(-101);
_.isFinite(-Infinity);
_.isBoolean(null);
_.isDate(new Date());
_.isRegExp(/moe/);
_.isNaN(NaN);
isNaN(undefined);
_.isNaN(undefined);
_.isNull(null);
_.isNull(undefined);
_.isUndefined(window.missingVariable);
///////////////////////////////////////////////////////////////////////////////////////
var underscore = _.noConflict();
var moe2 = { name: 'moe' };
moe2 === _.identity(moe);
var genie;
_(3).times(function(n){ genie.grantWishNumber(n); });
_.random(0, 100);
_.mixin({
capitalize: function (string) {
return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
}
});
_("fabio").capitalize();
_.uniqueId('contact_');
_.escape('Curly, Larry & Moe');
var object = { cheese: 'crumpets', stuff: function () { return 'nonsense'; } };
_.result(object, 'cheese');
_.result(object, 'stuff');
var compiled = _.template("hello: <%= name %>");
compiled({ name: 'moe' });
var list2 = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
_.template(list2, { people: ['moe', 'curly', 'larry'] });
var template = _.template("<b><%- value %></b>");
template({ value: '<script>' });
var compiled2 = _.template("<% print('Hello ' + epithet); %>");
compiled2({ epithet: "stooge" });
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
};
var template2 = _.template("Hello {{ name }}!");
template2({ name: "Mustache" });
_.template("Using 'with': <%= data.answer %>", { answer: 'no' }, { variable: 'data' });