diff --git a/box2d/box2dweb.d.ts b/box2d/box2dweb.d.ts index 8df8d6c90a..1126379803 100644 --- a/box2d/box2dweb.d.ts +++ b/box2d/box2dweb.d.ts @@ -1,5 +1,5 @@ /** -* Box2DWeb-2.1.d.ts Copyright (c) 2012 Josh Baldwin http://github.com/jbaldwin/box2dweb.d.ts +* Box2DWeb-2.1.d.ts Copyright (c) 2012-2013 Josh Baldwin http://github.com/jbaldwin/box2dweb.d.ts * There are a few competing javascript Box2D ports. * This definitions file is for Box2dWeb.js -> * http://code.google.com/p/box2dweb/ @@ -36,7 +36,7 @@ module Box2D.Common { * Color for debug drawing. Each value has the range [0, 1]. **/ export class b2Color { - + /** * Red **/ @@ -60,20 +60,23 @@ module Box2D.Common { /** * Constructor - * @rr Red value - * @gg Green value - * @bb Blue value + * @param rr Red value + * @param gg Green value + * @param bb Blue value **/ - constructor (rr: number, gg: number, bb: number); + constructor(rr: number, gg: number, bb: number); /** * Sets the Color to new RGB values. - * @rr Red value - * @gg Green value - * @bb Blue value + * @param rr Red value + * @param gg Green value + * @param bb Blue value **/ public Set(rr: number, gg: number, bb: number): void; } +} + +module Box2D.Common { /** * Controls Box2D global settings. @@ -82,6 +85,7 @@ module Box2D.Common { /** * b2Assert is used internally to handle assertions. By default, calls are commented out to save performance, so they serve more as documentation than anything else. + * @param a Asset an expression is true. **/ public static b2Assert(a: bool): void; @@ -89,8 +93,8 @@ module Box2D.Common { * Friction mixing law. Feel free to customize this. * Friction values are usually set between 0 and 1. (0 = no friction, 1 = high friction) * By default this is `return Math.sqrt(friction1, friction2);` - * @friction1 Friction 1 to mix. - * @friction2 Friction 2 to mix. + * @param friction1 Friction 1 to mix. + * @param friction2 Friction 2 to mix. * @return The two frictions mixed as one value. **/ public static b2MixFriction(friction1: number, friction2: number): number; @@ -99,8 +103,8 @@ module Box2D.Common { * Restitution mixing law. Feel free to customize this. Restitution is used to make objects bounce. * Restitution values are usually set between 0 and 1. (0 = no bounce (inelastic), 1 = perfect bounce (perfectly elastic)) * By default this is `return Math.Max(restitution1, restitution2);` - * @restitution1 Restitution 1 to mix. - * @restitution2 Restitution 2 to mix. + * @param restitution1 Restitution 1 to mix. + * @param restitution2 Restitution 2 to mix. * @return The two restitutions mixed as one value. **/ public static b2MixRestitution(restitution1: number, restitution2: number): number; @@ -244,7 +248,7 @@ module Box2D.Common.Math { /** * Empty constructor **/ - constructor (); + constructor(); /** * Sets all internal matrix values to absolute values. @@ -253,7 +257,7 @@ module Box2D.Common.Math { /** * Adds the two 2x2 matricies together and stores the result in this matrix. - * @m 2x2 matrix to add. + * @param m 2x2 matrix to add. **/ public AddM(m: b2Mat22): void; @@ -267,19 +271,19 @@ module Box2D.Common.Math { * Creates a rotation 2x2 matrix from the given angle. * R(theta) = [ cos(theta) -sin(theta) ] * [ sin(theta) cos(theta) ] - * @angle Matrix angle (theta). + * @param angle Matrix angle (theta). * @return 2x2 matrix. **/ public static FromAngle(angle: number): b2Mat22; - + /** * Creates a 2x2 matrix from two columns. - * @c1 Column 1 vector. - * @c2 Column 2 vector. + * @param c1 Column 1 vector. + * @param c2 Column 2 vector. * @return 2x2 matrix. **/ public static FromVV(c1: b2Vec2, c2: b2Vec2): b2Mat22; - + /** * Gets the rotation matrix angle. * R(theta) = [ cos(theta) -sin(theta) ] @@ -290,7 +294,7 @@ module Box2D.Common.Math { /** * Compute the inverse of this matrix, such that inv(A) A = identity. - * @out Inverse matrix. + * @param out Inverse matrix. * @return Inverse matrix. **/ public GetInverse(out: b2Mat22): b2Mat22; @@ -299,10 +303,10 @@ module Box2D.Common.Math { * Sets the 2x2 rotation matrix from the given angle. * R(theta) = [ cos(theta) -sin(theta) ] * [ sin(theta) cos(theta) ] - * @angle Matrix angle (theta). + * @param angle Matrix angle (theta). **/ public Set(angle: number): void; - + /** * Sets the 2x2 matrix to identity. **/ @@ -310,14 +314,14 @@ module Box2D.Common.Math { /** * Sets the 2x2 matrix from a 2x2 matrix. - * @m 2x2 matrix values. + * @param m 2x2 matrix values. **/ public SetM(m: b2Mat22): void; /** * Sets the 2x2 matrix from 2 column vectors. - * @c1 Column 1 vector. - * @c2 Column 2 vector. + * @param c1 Column 1 vector. + * @param c2 Column 2 vector. **/ public SetVV(c1: b2Vec2, c2: b2Vec2): void; @@ -328,13 +332,16 @@ module Box2D.Common.Math { /** * TODO, has something to do with the determinant - * @out Solved vector - * @bX - * @bY + * @param out Solved vector + * @param bX + * @param bY * @return Solved vector **/ public Solve(out: b2Vec2, bX: number, bY: number): b2Vec2; } +} + +module Box2D.Common.Math { /** * A 3-by3 matrix. Stored in column-major order. @@ -358,15 +365,15 @@ module Box2D.Common.Math { /** * Constructor - * @c1 Column 1 - * @c2 Column 2 - * @c3 Column 3 + * @param c1 Column 1 + * @param c2 Column 2 + * @param c3 Column 3 **/ - constructor (c1: b2Vec3, c2: b2Vec3, c3: b2Vec3); + constructor(c1: b2Vec3, c2: b2Vec3, c3: b2Vec3); /** * Adds the two 3x3 matricies together and stores the result in this matrix. - * @m 3x3 matrix to add. + * @param m 3x3 matrix to add. **/ public AddM(m: b2Mat33): void; @@ -383,15 +390,15 @@ module Box2D.Common.Math { /** * Sets the 3x3 matrix from a 3x3 matrix. - * @m 3x3 matrix values. + * @param m 3x3 matrix values. **/ public SetM(m: b2Mat33): void; /** * Sets the 3x3 matrix from 3 column vectors. - * @c1 Column 1 vector. - * @c2 Column 2 vector. - * @c3 Column 2 vector. + * @param c1 Column 1 vector. + * @param c2 Column 2 vector. + * @param c3 Column 2 vector. **/ public SetVVV(c1: b2Vec3, c2: b2Vec3, c3: b2Vec3): void; @@ -402,23 +409,26 @@ module Box2D.Common.Math { /** * TODO, has something to do with the determinant - * @out Solved vector - * @bX - * @bY + * @param out Solved vector + * @param bX + * @param bY * @return Solved vector **/ public Solve22(out: b2Vec2, bX: number, bY: number): b2Vec2; /** * TODO, has something to do with the determinant - * @out Solved vector - * @bX - * @bY - * @bZ + * @param out Solved vector + * @param bX + * @param bY + * @param bZ * @return Solved vector **/ public Solve33(out: b2Vec3, bX: number, bY: number, bZ: number): b2Vec3; } +} + +module Box2D.Common.Math { /** * Math utility functions. @@ -427,241 +437,241 @@ module Box2D.Common.Math { /** * Determines if a number is valid. A number is valid if it is finite. - * @x Number to check for validity. + * @param x Number to check for validity. * @return True if x is valid, otherwise false. **/ public static IsValid(x: number): bool; /** * Dot product of two vector 2s. - * @a Vector 2 to use in dot product. - * @b Vector 2 to use in dot product. + * @param a Vector 2 to use in dot product. + * @param b Vector 2 to use in dot product. * @return Dot product of a and b. **/ public static Dot(a: b2Vec2, b: b2Vec2): number; /** * Cross product of two vector 2s. - * @a Vector 2 to use in cross product. - * @b Vector 2 to use in cross product. + * @param a Vector 2 to use in cross product. + * @param b Vector 2 to use in cross product. * @return Cross product of a and b. **/ public static CrossVV(a: b2Vec2, b: b2Vec2): number; /** * Cross product of vector 2 and s. - * @a Vector 2 to use in cross product. - * @s s value. + * @param a Vector 2 to use in cross product. + * @param s s value. * @return Cross product of a and s. **/ public static CrossVF(a: b2Vec2, s: number): b2Vec2; /** * Cross product of s and vector 2. - * @s s value. - * @a Vector 2 to use in cross product. + * @param s s value. + * @param a Vector 2 to use in cross product. * @return Cross product of s and a. **/ public static CrossFV(s: number, a: b2Vec2): b2Vec2; /** * Multiply matrix and vector. - * @A Matrix. - * @v Vector. + * @param A Matrix. + * @param v Vector. * @return Result. **/ public static MulMV(A: b2Mat22, v: b2Vec2): b2Vec2; /** * - * @A - * @v + * @param A + * @param v * @return **/ public static MulTMV(A: b2Mat22, v: b2Vec2): b2Vec2; /** * - * @T - * @v + * @param T + * @param v * @return **/ public static MulX(T: b2Transform, v: b2Vec2): b2Vec2; /** * - * @T - * @v + * @param T + * @param v * @return **/ public static MulXT(T: b2Transform, v: b2Vec2): b2Vec2; /** * Adds two vectors. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return a + b. **/ public static AddVV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Subtracts two vectors. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return a - b. **/ public static SubtractVV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Calculates the distance between two vectors. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return Distance between a and b. **/ public static Distance(a: b2Vec2, b: b2Vec2): number; /** * Calculates the squared distance between two vectors. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return dist^2 between a and b. **/ public static DistanceSquared(a: b2Vec2, b: b2Vec2): number; /** * - * @s - * @a + * @param s + * @param a * @return **/ public static MulFV(s: number, a: b2Vec2): b2Vec2; /** * - * @A - * @B + * @param A + * @param B * @return **/ public static AddMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * - * @A - * @B + * @param A + * @param B * @return **/ public static MulMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * - * @A - * @B + * @param A + * @param B * @return **/ public static MulTMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * Creates an ABS number. - * @a Number to ABS. + * @param a Number to ABS. * @return Absolute value of a. **/ public static Abs(a: number): number; /** * Creates an ABS vector. - * @a Vector to ABS all values. + * @param a Vector to ABS all values. * @return Vector with all positive values. **/ public static AbsV(a: b2Vec2): b2Vec2; /** * Creates an ABS matrix. - * @A Matrix to ABS all values. + * @param A Matrix to ABS all values. * @return Matrix with all positive values. **/ public static AbsM(A: b2Mat22): b2Mat22; /** * Determines the minimum number. - * @a First number. - * @b Second number. + * @param a First number. + * @param b Second number. * @return a or b depending on which is the minimum. **/ public static Min(a: number, b: number): number; /** * Determines the minimum vector. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return a or b depending on which is the minimum. **/ public static MinV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Determines the max number. - * @a First number. - * @b Second number. + * @param a First number. + * @param b Second number. * @return a or b depending on which is the maximum. **/ public static Max(a: number, b: number): number; /** * Determines the max vector. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return a or b depending on which is the maximum. **/ public static MaxV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Clamp a number to the range of low to high. - * @a Number to clamp. - * @low Low range. - * @high High range. + * @param a Number to clamp. + * @param low Low range. + * @param high High range. * @return Number a clamped to range of low to high. **/ public static Clamp(a: number, low: number, high: number): number; /** * Clamps a vector to the range of low to high. - * @a Vector to clamp. - * @low Low range. - * @high High range. + * @param a Vector to clamp. + * @param low Low range. + * @param high High range. * @return Vector a clamped to range of low to high. **/ public static ClampV(a: b2Vec2, low: b2Vec2, high: b2Vec2): b2Vec2; /** * Swaps a and b objects. - * @a a -> b. - * @b b -> a. + * @param a a -> b. + * @param b b -> a. **/ public static Swap(a: any, b: any): void; /** * Generates a random number. - * @return Random number. + * @param return Random number. **/ public static Random(): number; /** * Returns a random number between lo and hi. - * @lo Lowest random number. - * @hi Highest random number. + * @param lo Lowest random number. + * @param hi Highest random number. * @return Number between lo and hi. **/ public static RandomRange(lo: number, hi: number): number; /** * Calculates the next power of 2 after the given number. - * @x Number to start search for the next power of 2. + * @param x Number to start search for the next power of 2. * @return The next number that is a power of 2. **/ public static NextPowerOfTwo(x: number): number; /** * Check if a number is a power of 2. - * @x Number to check if it is a power of 2. + * @param x Number to check if it is a power of 2. * @return True if x is a power of 2, otherwise false. **/ public static IsPowerOfTwo(x: number): bool; @@ -681,6 +691,9 @@ module Box2D.Common.Math { **/ public static b2Transform_identity: b2Transform; } +} + +module Box2D.Common.Math { /** * This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to the body origin, which may no coincide with the center of mass. However, to support dynamics we must interpolate the center of mass position. @@ -706,12 +719,12 @@ module Box2D.Common.Math { * Center world position. **/ public c0: b2Vec2; - + /** * Local center of mass position. **/ public localCenter: b2Vec2; - + /** * Time interval = [t0,1], where t0 is in [0,1]. **/ @@ -730,17 +743,20 @@ module Box2D.Common.Math { /** * Get the interpolated transform at a specific time. - * @xf Transform at specified time, this is an out parameter. - * @alpha Is a factor in [0,1], where 0 indicates t0. + * @param xf Transform at specified time, this is an out parameter. + * @param alpha Is a factor in [0,1], where 0 indicates t0. **/ public GetTransform(xf: b2Transform, alpha: number): void; /** * Sets the sweep from a sweep. - * @other Sweep values to copy from. + * @param other Sweep values to copy from. **/ public Set(other: b2Sweep): void; } +} + +module Box2D.Common.Math { /** * A transform contains translation and rotation. It is used to represent the position and orientation of rigid frames. @@ -759,10 +775,10 @@ module Box2D.Common.Math { /** * The default constructor does nothing (for performance). - * @pos Position - * @r Rotation + * @param pos Position + * @param r Rotation **/ - constructor (pos: b2Vec2, r: b2Mat22); + constructor(pos: b2Vec2, r: b2Mat22); /** * Calculate the angle that the rotation matrix represents. @@ -772,14 +788,14 @@ module Box2D.Common.Math { /** * Initialize using a position vector and rotation matrix. - * @pos Position - * @r Rotation + * @param pos Position + * @param r Rotation **/ public Initialize(pos: b2Vec2, r: b2Mat22): void; /** * Sets the transfrom from a transfrom. - * @x Transform to copy values from. + * @param x Transform to copy values from. **/ public Set(x: b2Transform): void; @@ -788,6 +804,9 @@ module Box2D.Common.Math { **/ public SetIdentity(): void; } +} + +module Box2D.Common.Math { /** * A 2D column vector. @@ -806,10 +825,10 @@ module Box2D.Common.Math { /** * Creates a new vector 2. - * @x x value, default = 0. - * @y y value, default = 0. + * @param x x value, default = 0. + * @param y y value, default = 0. **/ - constructor (x?: number, y?: number); + constructor(x?: number, y?: number); /** * Sets x and y to absolute values. @@ -818,7 +837,7 @@ module Box2D.Common.Math { /** * Adds the vector 2 to this vector 2. The result is stored in this vector 2. - * @v Vector 2 to add. + * @param v Vector 2 to add. **/ public Add(v: b2Vec2): void; @@ -830,13 +849,13 @@ module Box2D.Common.Math { /** * Cross F V - * @s + * @param s **/ public CrossFV(s: number): void; /** * Cross V F - * @s + * @param s **/ public CrossVF(s: number): void; @@ -866,38 +885,38 @@ module Box2D.Common.Math { /** * Creates a new vector 2 from the given values. - * @x x value. - * @y y value. + * @param x x value. + * @param y y value. **/ public static Make(x: number, y: number): b2Vec2; /** * Calculates which vector has the maximum values and sets this vector to those values. - * @b Vector 2 to compare for maximum values. + * @param b Vector 2 to compare for maximum values. **/ public MaxV(b: b2Vec2): void; /** * Calculates which vector has the minimum values and sets this vector to those values. - * @b Vector 2 to compare for minimum values. + * @param b Vector 2 to compare for minimum values. **/ public MinV(b: b2Vec2): void; /** * Matrix multiplication. Stores the result in this vector 2. - * @A Matrix to muliply by. + * @param A Matrix to muliply by. **/ public MulM(A: b2Mat22): void; /** * Vector multiplication. Stores the result in this vector 2. - * @a Value to multiple the vector's values by. + * @param a Value to multiple the vector's values by. **/ public Multiply(a: number): void; /** * Dot product multiplication. Stores the result in this vector 2. - * @A Matrix to multiply by. + * @param A Matrix to multiply by. **/ public MulTM(A: b2Mat22): void; @@ -914,14 +933,14 @@ module Box2D.Common.Math { /** * Sets the vector 2. - * @x x value, default is 0. - * @y y value, default is 0. + * @param x x value, default is 0. + * @param y y value, default is 0. **/ public Set(x?: number, y?: number): void; /** * Sets the vector 2 from a vector 2. - * @v Vector 2 to copy values from. + * @param v Vector 2 to copy values from. **/ public SetV(v: b2Vec2): void; @@ -932,10 +951,13 @@ module Box2D.Common.Math { /** * Subtracts the vector 2 from this vector 2. The result is stored in this vector 2. - * @v Vector 2 to subtract. + * @param v Vector 2 to subtract. **/ public Subtract(v: b2Vec2): void; } +} + +module Box2D.Common.Math { /** * A 2D column vector with 3 elements. @@ -959,15 +981,15 @@ module Box2D.Common.Math { /** * Construct using coordinates x,y,z. - * @x x value, default = 0. - * @y y value, default = 0. - * @z z value, default = 0. + * @param x x value, default = 0. + * @param y y value, default = 0. + * @param z z value, default = 0. **/ - constructor (x?: number, y?: number, z?: number); + constructor(x?: number, y?: number, z?: number); /** * Adds the vector 3 to this vector 3. The result is stored in this vector 3. - * @v Vector 3 to add. + * @param v Vector 3 to add. **/ public Add(v: b2Vec3): void; @@ -985,7 +1007,7 @@ module Box2D.Common.Math { /** * Vector multiplication. Stores the result in this vector 3. - * @a Value to multiple the vector's values by. + * @param a Value to multiple the vector's values by. **/ public Multiply(a: number): void; @@ -996,15 +1018,15 @@ module Box2D.Common.Math { /** * Sets the vector 3. - * @x x value, default is 0. - * @y y value, default is 0. - * @z z value, default is 0. + * @param x x value, default is 0. + * @param y y value, default is 0. + * @param z z value, default is 0. **/ public Set(x?: number, y?: number, z?: number): void; /** * Sets the vector 3 from a vector 3. - * @v Vector 3 to copy values from. + * @param v Vector 3 to copy values from. **/ public SetV(v: b2Vec3): void; @@ -1015,7 +1037,7 @@ module Box2D.Common.Math { /** * Subtracts the vector 3 from this vector 3. The result is stored in this vector 3. - * @v Vector 3 to subtract. + * @param v Vector 3 to subtract. **/ public Subtract(v: b2Vec3): void; } @@ -1040,22 +1062,22 @@ module Box2D.Collision { /** * Combines two AABBs into one with max values for upper bound and min values for lower bound. - * @aabb1 First AABB to combine. - * @aabb2 Second AABB to combine. + * @param aabb1 First AABB to combine. + * @param aabb2 Second AABB to combine. * @return New AABB with max values from aabb1 and aabb2. **/ public static Combine(aabb1: b2AABB, aabb2: b2AABB): b2AABB; /** * Combines two AABBs into one with max values for upper bound and min values for lower bound. The result is stored in this AABB. - * @aabb1 First AABB to combine. - * @aabb2 Second AABB to combine. + * @param aabb1 First AABB to combine. + * @param aabb2 Second AABB to combine. **/ public Combine(aabb1: b2AABB, aabb2: b2AABB): void; /** * Determines if an AABB is contained within this one. - * @aabb AABB to see if it is contained. + * @param aabb AABB to see if it is contained. * @return True if aabb is contained, otherwise false. **/ public Contains(aabb: b2AABB): bool; @@ -1080,19 +1102,22 @@ module Box2D.Collision { /** * Perform a precise raycast against this AABB. - * @output Ray cast output values. - * @input Ray cast input values. + * @param output Ray cast output values. + * @param input Ray cast input values. * @return True if the ray cast hits this AABB, otherwise false. **/ public RayCast(output: b2RayCastOutput, input: b2RayCastInput): bool; /** * Tests if another AABB overlaps this AABB. - * @other Other AABB to test for overlap. + * @param other Other AABB to test for overlap. * @return True if other overlaps this AABB, otherwise false. **/ public TestOverlap(other: b2AABB): bool; } +} + +module Box2D.Collision { /** * We use contact ids to facilitate warm starting. @@ -1122,10 +1147,13 @@ module Box2D.Collision { /** * Sets the Contact ID from a Contact ID. - * @id The Contact ID to copy values from. + * @param id The Contact ID to copy values from. **/ public Set(id: b2ContactID): void; } +} + +module Box2D.Collision { /** * This structure is used to report contact points. @@ -1136,7 +1164,7 @@ module Box2D.Collision { * The combined friction coefficient. **/ public friction: number; - + /** * The contact id identifies the features in contact. **/ @@ -1177,6 +1205,9 @@ module Box2D.Collision { **/ public velocity: b2Math.b2Vec2; } +} + +module Box2D.Collision { /** * Input for b2Distance. You have to option to use the shape radii in the computation. Even @@ -1208,12 +1239,15 @@ module Box2D.Collision { **/ public useRadii: bool; } +} + +module Box2D.Collision { /** * Output calculation for b2Distance. **/ export class b2DistanceOutput { - + /** * Calculated distance. **/ @@ -1234,12 +1268,15 @@ module Box2D.Collision { **/ public pointB: b2Math.b2Vec2; } +} + +module Box2D.Collision { /** * A distance proxy is used by the GJK algorithm. It encapsulates any shape. **/ export class b2DistanceProxy { - + /** * Count **/ @@ -1257,20 +1294,21 @@ module Box2D.Collision { /** * Get the supporting vertex index in the given direction. - * @d Direction to look for the supporting vertex. + * @param d Direction to look for the supporting vertex. * @return Supporting vertex index. **/ public GetSupport(d: b2Math.b2Vec2): number; /** * Get the supporting vertex in the given direction. - * @d Direction to look for the supporting vertex. + * @param d Direction to look for the supporting vertex. * @return Supporting vertex. **/ public GetSupportVertex(d: b2Math.b2Vec2): b2Math.b2Vec2; /** * Get a vertex by index. Used by b2Distance. + * @param index Vetex's index. * @return Vertex at the given index. **/ public GetVertex(index: number): b2Math.b2Vec2; @@ -1283,10 +1321,13 @@ module Box2D.Collision { /** * Initialize the proxy using the given shape. The shape must remain in scope while the proxy is in use. - * @shape Shape to initialize the distance proxy. + * @param shape Shape to initialize the distance proxy. **/ public Set(shape: Shapes.b2Shape): void; } +} + +module Box2D.Collision { /** * A dynamic tree arranges data in a binary tree to accelerate queries such as volume queries and ray casts. Leafs are proxies with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor so that the proxy AABB is bigger than the client object. This allows the client object to move by small amounts without triggering a tree update. Nodes are pooled. @@ -1296,25 +1337,25 @@ module Box2D.Collision { /** * Constructing the tree initializes the node pool. **/ - constructor (); + constructor(); /** * Create a proxy. Provide a tight fitting AABB and a userData. - * @aabb AABB. - * @userDate User defined data for this proxy. + * @param aabb AABB. + * @param userDate User defined data for this proxy. * @return Dynamic tree node. **/ public CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** * Destroy a proxy. This asserts if the id is invalid. - * @proxy Proxy to destroy. + * @param proxy Proxy to destroy. **/ public DestroyProxy(proxy: b2DynamicTreeNode): void; /** * Gets the Fat AABB for the proxy. - * @proxy Proxy to retrieve Fat AABB. + * @param proxy Proxy to retrieve Fat AABB. * @return Fat AABB for proxy. **/ public GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; @@ -1322,43 +1363,46 @@ module Box2D.Collision { /** * Get user data from a proxy. Returns null if the proxy is invalid. * Cast to your type on return. - * @proxy Proxy to retrieve user data from. + * @param proxy Proxy to retrieve user data from. * @return User data for proxy or null if proxy is invalid. **/ public GetUserData(proxy: b2DynamicTreeNode): any; /** * Move a proxy with a swept AABB. If the proxy has moved outside of its fattened AABB, then the proxy is removed from the tree and re-inserted. Otherwise the function returns immediately. - * @proxy Proxy to move. - * @aabb Swept AABB. - * @displacement Extra AABB displacement. + * @param proxy Proxy to move. + * @param aabb Swept AABB. + * @param displacement Extra AABB displacement. **/ public MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: b2Math.b2Vec2): bool; /** * Query an AABB for overlapping proxies. The callback is called for each proxy that overlaps the supplied AABB. The callback should match function signature fuction callback(proxy:b2DynamicTreeNode):Boolean and should return false to trigger premature termination. - * @callback Called for each proxy that overlaps the supplied AABB. - * @proxy Proxy overlapping the supplied AABB. + * @param callback Called for each proxy that overlaps the supplied AABB. + * param proxy Proxy overlapping the supplied AABB. * @aabb Proxies are query for overlap on this AABB. **/ public Query(callback: (proxy: b2DynamicTreeNode) => bool, aabb: b2AABB): void; /** * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact ray-cast in the case were the proxy contains a shape. The callback also performs the any collision filtering. This has performance roughly equal to k log(n), where k is the number of collisions and n is the number of proxies in the tree. - * @callback Called for each proxy that is hit by the ray. - * @input Ray cast input data. - * @proxy The proxy hit by the ray cast. - * @return Return value is the new value for maxFraction. - * @input Ray cast input data. Query all proxies along this ray cast. + * @param callback Called for each proxy that is hit by the ray. + * param input Ray cast input data. + * param proxy The proxy hit by the ray cast. + * return Return value is the new value for maxFraction. + * @param input Ray cast input data. Query all proxies along this ray cast. **/ public RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** * Perform some iterations to re-balance the tree. - * @iterations Number of rebalance iterations to perform. + * @param iterations Number of rebalance iterations to perform. **/ public Rebalance(iterations: number): void; } +} + +module Box2D.Collision { /** * The broad-phase is used for computing pairs and performing volume queries and ray casts. This broad-phase does not persist pairs. Instead, this reports potentially new pairs. It is up to the client to consume the new pairs and to track subsequent overlap. @@ -1368,87 +1412,68 @@ module Box2D.Collision { /** * Creates the dynamic tree broad phase. **/ - constructor (); + constructor(); /** - * Create a proxy with an initial AABB. Pairs are not reported until UpdatePairs is called. - * @aabb Proxy Fat AABB. - * @userData User defined data. - * @return Proxy created from aabb and userData. + * @see IBroadPhase.CreateProxy **/ public CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** - * Destroy a proxy. It is up to the client to remove any pairs. - * @proxy Proxy to destroy. + * @see IBroadPhase.DestroyProxy **/ public DestroyProxy(proxy: b2DynamicTreeNode): void; - + /** - * Get the Fat AABB for a proxy. - * @proxy Proxy to retrieve the Fat AABB. + * @see IBroadPhase.GetFatAABB **/ public GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; /** - * Get the number of proxies. - * @return Number of proxies. + * @see IBroadPhase.GetProxyCount **/ public GetProxyCount(): number; /** - * Get user data from a proxy. Returns null if the proxy is invalid. - * @return Gets the user data from proxy, or null if the proxy is invalid. + * @see IBroadPhase.GetUserData **/ public GetUserData(proxy: b2DynamicTreeNode): any; /** - * Call MoveProxy as many times as you like, then when you are done call UpdatePairs to finalized the proxy pairs (for your time step). - * @proxy Proxy to move. - * @aabb Swept AABB. - * @displacement Extra AABB displacement. + * @see IBroadPhase.MoveProxy **/ public MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: b2Math.b2Vec2): void; /** - * Query an AABB for overlapping proxies. The callback is called for each proxy that overlaps the supplied AABB. The callback should match function signature fuction callback(proxy:b2DynamicTreeNode):Boolean and should return false to trigger premature termination. - * @callback Called for each proxy that overlaps the supplied AABB. - * @proxy Proxy overlapping the supplied AABB. - * @aabb Proxies are query for overlap on this AABB. + * @see IBroadPhase.Query **/ public Query(callback: (proxy: b2DynamicTreeNode) => bool, aabb: b2AABB): void; /** - * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact ray-cast in the case were the proxy contains a shape. The callback also performs the any collision filtering. This has performance roughly equal to k log(n), where k is the number of collisions and n is the number of proxies in the tree. - * @callback Called for each proxy that is hit by the ray. - * @input Ray cast input data. - * @proxy The proxy hit by the ray cast. - * @return Return value is the new value for maxFraction. - * @input Ray cast input data. Query all proxies along this ray cast. + * @see IBroadPhase.RayCast **/ public RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** - * Perform some iterations to re-balance the tree. - * @iterations Number of rebalance iterations to perform. + * @see IBroadPhase.Rebalance **/ public Rebalance(iterations: number): void; /** * Tests if two proxies overlap. - * @proxyA First proxy to test. - * @proxyB Second proxy to test. + * @param proxyA First proxy to test. + * @param proxyB Second proxy to test. * @return True if the proxyA and proxyB overlap with Fat AABBs, otherwise false. **/ public TestOverlap(proxyA: b2DynamicTreeNode, proxyB: b2DynamicTreeNode): bool; /** * Update the pairs. This results in pair callbacks. This can only add pairs. - * @callback Called for all new proxy pairs. - * @userDataA Proxy A in the pair user data. - * @userDataB Proxy B in the pair user data. + * @param callback Called for all new proxy pairs. + * param userDataA Proxy A in the pair user data. + * param userDataB Proxy B in the pair user data. **/ - public UpdatePairs(callback: (userDataA: any, userDataB: any) => void): void; + public UpdatePairs(callback: (userDataA: any, userDataB: any) => void ): void; /** * Validates the dynamic tree. @@ -1456,6 +1481,9 @@ module Box2D.Collision { **/ public Validate(): void; } +} + +module Box2D.Collision { /** * Empty declaration, used in many callbacks within b2DynamicTree. @@ -1464,6 +1492,9 @@ module Box2D.Collision { export class b2DynamicTreeNode { } +} + +module Box2D.Collision { /** * A manifold for two touching convex shapes. Box2D supports multiple types of contact: - clip point versus plane with radius - point versus point with radius (circles) The local point usage depends on the manifold type: -e_circles: the local center of circleA -e_faceA: the center of faceA -e_faceB: the center of faceB Similarly the local normal usage: -e_circles: not used -e_faceA: the normal on polygonA -e_faceB: the normal on polygonB We store contacts in this way so that position correction can account for movement, which is critical for continuous physics. All contact scenarios must be expressed in one of these types. This structure is stored across time steps, so we keep it small. @@ -1513,7 +1544,7 @@ module Box2D.Collision { /** * Creates a new manifold. **/ - constructor (); + constructor(); /** * Copies the manifold. @@ -1528,10 +1559,13 @@ module Box2D.Collision { /** * Sets this manifold from another manifold. - * @m Manifold to copy values from. + * @param m Manifold to copy values from. **/ public Set(m: b2Manifold): void; } +} + +module Box2D.Collision { /** * A manifold point is a contact point belonging to a contact manifold. It holds details related to the geometry and dynamics of the contact points. The local point usage depends on the manifold type: -e_circles: the local center of circleB -e_faceA: the local center of cirlceB or the clip point of polygonB -e_faceB: the clip point of polygonA This structure is stored across time steps, so we keep it small. Note: the impulses are used for internal caching and may not provide reliable contact forces, especially for high speed collisions. @@ -1547,7 +1581,7 @@ module Box2D.Collision { * Local contact point. **/ public m_localpoint: b2Math.b2Vec2; - + /** * Normal impluse for this contact point. **/ @@ -1561,7 +1595,7 @@ module Box2D.Collision { /** * Creates a new manifold point. **/ - constructor (); + constructor(); /** * Resets this manifold point. @@ -1570,10 +1604,13 @@ module Box2D.Collision { /** * Sets this manifold point from a manifold point. - * @m The manifold point to copy values from. + * @param m The manifold point to copy values from. **/ public Set(m: b2ManifoldPoint): void; } +} + +module Box2D.Collision { /** * An oriented bounding box. @@ -1595,6 +1632,9 @@ module Box2D.Collision { **/ public R: b2Math.b2Mat22; } +} + +module Box2D.Collision { /** * Ray cast input data. @@ -1615,15 +1655,18 @@ module Box2D.Collision { * The end point of the ray. **/ public p2: b2Math.b2Vec2; - + /** * Creates a new ray cast input. - * @p1 Start point of the ray, default = null. - * @p2 End point of the ray, default = null. - * @maxFraction Truncate the ray to reach up to this fraction from p1 to p2. + * @param p1 Start point of the ray, default = null. + * @param p2 End point of the ray, default = null. + * @param maxFraction Truncate the ray to reach up to this fraction from p1 to p2. **/ - constructor (p1?: b2Math.b2Vec2, p2?: b2Math.b2Vec2, maxFraction?: number); + constructor(p1?: b2Math.b2Vec2, p2?: b2Math.b2Vec2, maxFraction?: number); } +} + +module Box2D.Collision { /** * Results of a ray cast. @@ -1640,6 +1683,9 @@ module Box2D.Collision { **/ public normal: b2Math.b2Vec2; } +} + +module Box2D.Collision { /** * A line in space between two given vertices. @@ -1658,27 +1704,27 @@ module Box2D.Collision { /** * Extends or clips the segment so that it's ends lie on the boundary of the AABB. - * @aabb AABB to extend/clip the segement. + * @param aabb AABB to extend/clip the segement. **/ public Extend(aabb: b2AABB): void; /** * See Extend, this works on the ending point. - * @aabb AABB to extend/clip the ending point. + * @param aabb AABB to extend/clip the ending point. **/ public ExtendBackward(aabb: b2AABB): void; /** * See Extend, this works on the starting point. - * @aabb AABB to extend/clip the starting point. + * @param aabb AABB to extend/clip the starting point. **/ public ExtendForward(aabb: b2AABB): void; /** * Ray cast against this segment with another segment. - * @lambda returns the hit fraction. You can use this to compute the contact point * p = (1 - lambda) * segment.p1 + lambda * segment.p2 * @normal Normal at the contact point. If there is no intersection, the normal is not set. - * @segment Defines the begining and end point of the ray cast. - * @maxLambda a number typically in the range [0,1]. + * @param lambda returns the hit fraction. You can use this to compute the contact point * p = (1 - lambda) * segment.p1 + lambda * segment.p2 * @normal Normal at the contact point. If there is no intersection, the normal is not set. + * @param segment Defines the begining and end point of the ray cast. + * @param maxLambda a number typically in the range [0,1]. * @return True if there is an intersection, otherwise false. **/ public TestSegment( @@ -1687,6 +1733,9 @@ module Box2D.Collision { segment: b2Segment, maxLambda: number): bool; } +} + +module Box2D.Collision { /** * Used to warm start b2Distance. Set count to zero on first call. @@ -1713,6 +1762,9 @@ module Box2D.Collision { **/ public metric: number; } +} + +module Box2D.Collision { /** * Inpute parameters for b2TimeOfImpact @@ -1744,6 +1796,9 @@ module Box2D.Collision { **/ public tolerance: number; } +} + +module Box2D.Collision { /** * This is used to compute the current state of a contact manifold. @@ -1763,15 +1818,15 @@ module Box2D.Collision { /** * Creates a new b2WorldManifold. **/ - constructor (); + constructor(); /** * Evaluate the manifold with supplied transforms. This assumes modest motion from the original state. This does not change the point count, impulses, etc. The radii must come from the shapes that generated the manifold. - * @manifold Manifold to evaluate. - * @xfA A transform. - * @radiusA A radius. - * @xfB B transform. - * @radiusB B radius. + * @param manifold Manifold to evaluate. + * @param xfA A transform. + * @param radiusA A radius. + * @param xfB B transform. + * @param radiusB B radius. **/ public Initialize( manifold: b2Manifold, @@ -1780,6 +1835,9 @@ module Box2D.Collision { xfB: b2Math.b2Transform, radiusB: number): void; } +} + +module Box2D.Collision { /** * We use contact ids to facilitate warm starting. @@ -1806,29 +1864,32 @@ module Box2D.Collision { **/ public referenceEdge: number; } +} + +module Box2D.Collision { /** * Interface for objects tracking overlap of many AABBs. **/ export interface IBroadPhase { - + /** * Create a proxy with an initial AABB. Pairs are not reported until UpdatePairs is called. - * @aabb Proxy Fat AABB. - * @userData User defined data. + * @param aabb Proxy Fat AABB. + * @param userData User defined data. * @return Proxy created from aabb and userData. **/ CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** * Destroy a proxy. It is up to the client to remove any pairs. - * @proxy Proxy to destroy. + * @param proxy Proxy to destroy. **/ DestroyProxy(proxy: b2DynamicTreeNode): void; /** * Get the Fat AABB for a proxy. - * @proxy Proxy to retrieve the Fat AABB. + * @param proxy Proxy to retrieve the Fat AABB. **/ GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; @@ -1840,39 +1901,40 @@ module Box2D.Collision { /** * Get user data from a proxy. Returns null if the proxy is invalid. + * @param proxy Proxy to retrieve user data from. * @return Gets the user data from proxy, or null if the proxy is invalid. **/ GetUserData(proxy: b2DynamicTreeNode): any; /** * Call MoveProxy as many times as you like, then when you are done call UpdatePairs to finalized the proxy pairs (for your time step). - * @proxy Proxy to move. - * @aabb Swept AABB. - * @displacement Extra AABB displacement. + * @param proxy Proxy to move. + * @param aabb Swept AABB. + * @param displacement Extra AABB displacement. **/ MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: b2Math.b2Vec2): void; - + /** * Query an AABB for overlapping proxies. The callback is called for each proxy that overlaps the supplied AABB. The callback should match function signature fuction callback(proxy:b2DynamicTreeNode):Boolean and should return false to trigger premature termination. - * @callback Called for each proxy that overlaps the supplied AABB. - * @proxy Proxy overlapping the supplied AABB. - * @aabb Proxies are query for overlap on this AABB. + * @param callback Called for each proxy that overlaps the supplied AABB. + * param proxy Proxy overlapping the supplied AABB. + * @param aabb Proxies are query for overlap on this AABB. **/ Query(callback: (proxy: b2DynamicTreeNode) => bool, aabb: b2AABB): void; /** * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact ray-cast in the case were the proxy contains a shape. The callback also performs the any collision filtering. This has performance roughly equal to k log(n), where k is the number of collisions and n is the number of proxies in the tree. - * @callback Called for each proxy that is hit by the ray. - * @input Ray cast input data. - * @proxy The proxy hit by the ray cast. - * @return Return value is the new value for maxFraction. - * @input Ray cast input data. Query all proxies along this ray cast. + * @param callback Called for each proxy that is hit by the ray. + * param input Ray cast input data. + * param proxy The proxy hit by the ray cast. + * param return Return value is the new value for maxFraction. + * @param input Ray cast input data. Query all proxies along this ray cast. **/ RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** * Perform some iterations to re-balance the tree. - * @iterations Number of rebalance iterations to perform. + * @param iterations Number of rebalance iterations to perform. **/ Rebalance(iterations: number): void; } @@ -1887,28 +1949,30 @@ module Box2D.Collision.Shapes { /** * Creates a new circle shape. + * @param radius Circle radius. **/ - constructor (radius?:number); + constructor(radius?: number); /** * Given a transform, compute the associated axis aligned bounding box for this shape. - * @aabb Calculated AABB, this argument is `out`. - * @xf Transform to calculate the AABB. + * @param aabb Calculated AABB, this argument is `out`. + * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. - * @massData Calculate the mass, this argument is `out`. + * @param massData Calculate the mass, this argument is `out`. + * @param density **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane - * @normal The surface normal. - * @offset The surface offset along the normal. - * @xf The shape transform. - * @c The centroid, this argument is `out`. + * @param normal The surface normal. + * @param offset The surface offset along the normal. + * @param xf The shape transform. + * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Math.b2Vec2, @@ -1936,9 +2000,9 @@ module Box2D.Collision.Shapes { /** * Cast a ray against this shape. - * @output Ray cast results, this argument is `out`. - * @input Ray cast input parameters. - * @transform The transform to be applied to the shape. + * @param output Ray cast results, this argument is `out`. + * @param input Ray cast input parameters. + * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ public RayCast( @@ -1948,30 +2012,33 @@ module Box2D.Collision.Shapes { /** * Set the circle shape values from another shape. - * @other The other circle shape to copy values from. + * @param other The other circle shape to copy values from. **/ public Set(other: b2CircleShape): void; /** * Set the local position of this circle in its parent body. - * @position The new local position of this circle. + * @param position The new local position of this circle. **/ public SetLocalPosition(position: b2Math.b2Vec2): void; /** * Set the radius of the circle. - * @radius The new radius of the circle. + * @param radius The new radius of the circle. **/ public SetRadius(radius: number): void; - + /** * Test a point for containment in this shape. This only works for convex shapes. - * @xf Shape world transform. - * @p Point to test against, in world coordinates. + * @param xf Shape world transform. + * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Math.b2Transform, p: b2Math.b2Vec2): bool; } +} + +module Box2D.Collision.Shapes { /** * This structure is used to build edge shapes. @@ -1996,8 +2063,11 @@ module Box2D.Collision.Shapes { /** * Creates a new edge chain def. **/ - constructor (); + constructor(); } +} + +module Box2D.Collision.Shapes { /** * An edge shape. @@ -2006,28 +2076,30 @@ module Box2D.Collision.Shapes { /** * Creates a new edge shape. + * @param v1 First vertex + * @param v2 Second vertex **/ - constructor (v1: b2Math.b2Vec2, v2: b2Math.b2Vec2); + constructor(v1: b2Math.b2Vec2, v2: b2Math.b2Vec2); /** * Given a transform, compute the associated axis aligned bounding box for this shape. - * @aabb Calculated AABB, this argument is `out`. - * @xf Transform to calculate the AABB. + * @param aabb Calculated AABB, this argument is `out`. + * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. - * @massData Calculate the mass, this argument is `out`. + * @param massData Calculate the mass, this argument is `out`. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane - * @normal The surface normal. - * @offset The surface offset along the normal. - * @xf The shape transform. - * @c The centroid, this argument is `out`. + * @param normal The surface normal. + * @param offset The surface offset along the normal. + * @param xf The shape transform. + * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Math.b2Vec2, @@ -2103,6 +2175,7 @@ module Box2D.Collision.Shapes { /** * Get the first vertex and apply the supplied transform. + * @param xf Transform to apply. * @return First vertex with xf transform applied. **/ public GetFirstVertex(xf: b2Math.b2Transform): b2Math.b2Vec2; @@ -2121,18 +2194,18 @@ module Box2D.Collision.Shapes { /** * Get the support point in the given world direction with the supplied transform. - * @xf Transform to apply. - * @dX X world direction. - * @dY Y world direction. + * @param xf Transform to apply. + * @param dX X world direction. + * @param dY Y world direction. * @return Support point. **/ public Support(xf: b2Math.b2Transform, dX: number, dY: number): b2Math.b2Vec2; /** * Cast a ray against this shape. - * @output Ray cast results, this argument is `out`. - * @input Ray cast input parameters. - * @transform The transform to be applied to the shape. + * @param output Ray cast results, this argument is `out`. + * @param input Ray cast input parameters. + * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ public RayCast( @@ -2142,12 +2215,15 @@ module Box2D.Collision.Shapes { /** * Test a point for containment in this shape. This only works for convex shapes. - * @xf Shape world transform. - * @p Point to test against, in world coordinates. + * @param xf Shape world transform. + * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Math.b2Transform, p: b2Math.b2Vec2): bool; } +} + +module Box2D.Collision.Shapes { /** * This holds the mass data computed for a shape. @@ -2169,73 +2245,76 @@ module Box2D.Collision.Shapes { **/ public mass: number; } +} + +module Box2D.Collision.Shapes { /** * Convex polygon. The vertices must be in CCW order for a right-handed coordinate system with the z-axis coming out of the screen. **/ export class b2PolygonShape extends b2Shape { - + /** * Creates a b2PolygonShape from a vertices list. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. - * @vertices List of vertices to create the polygon shape from. - * @vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. + * @param vertices List of vertices to create the polygon shape from. + * @param vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public static AsArray(vertices: b2Math.b2Vec2[], vertexCount?: number): b2PolygonShape; /** * Build vertices to represent an axis-aligned box. - * @hx The half-width. - * @hy The half-height. + * @param hx The half-width. + * @param hy The half-height. * @return Box polygon shape. **/ public static AsBox(hx: number, hy: number): b2PolygonShape; /** * Creates a single edge from two vertices. - * @v1 First vertex. - * @v2 Second vertex. + * @param v1 First vertex. + * @param v2 Second vertex. * @return Edge polygon shape. **/ public static AsEdge(v1: b2Math.b2Vec2, b2: b2Math.b2Vec2): b2PolygonShape; /** * Build vertices to represent an oriented box. - * @hx The half-width. - * @hy The half-height. - * @center The center of the box in local coordinates, default is null (no center?) - * @angle The rotation of the box in local coordinates, default is 0.0. + * @param hx The half-width. + * @param hy The half-height. + * @param center The center of the box in local coordinates, default is null (no center?) + * @param angle The rotation of the box in local coordinates, default is 0.0. * @return Oriented box shape. **/ public static AsOrientedBox(hx: number, hy: number, center?: b2Math.b2Vec2, angle?: number): b2PolygonShape; /** * This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. - * @vertices List of vertices to create the polygon shape from. - * @vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. + * @param vertices List of vertices to create the polygon shape from. + * @param vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public static AsVector(vertices: b2Math.b2Vec2[], vertexCount?: number): b2PolygonShape; /** * Given a transform, compute the associated axis aligned bounding box for this shape. - * @aabb Calculated AABB, this argument is `out`. - * @xf Transform to calculate the AABB. + * @param aabb Calculated AABB, this argument is `out`. + * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. - * @massData Calculate the mass, this argument is `out`. + * @param massData Calculate the mass, this argument is `out`. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane - * @normal The surface normal. - * @offset The surface offset along the normal. - * @xf The shape transform. - * @c The centroid, this argument is `out`. + * @param normal The surface normal. + * @param offset The surface offset along the normal. + * @param xf The shape transform. + * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Math.b2Vec2, @@ -2256,14 +2335,14 @@ module Box2D.Collision.Shapes { /** * Get the supporting vertex index in the given direction. - * @d Direction to look. + * @param d Direction to look. * @return Vertex index supporting the direction. **/ public GetSupport(d: b2Math.b2Vec2): number; /** * Get the supporting vertex in the given direction. - * @d Direciton to look. + * @param d Direciton to look. * @return Vertex supporting the direction. **/ public GetSupportVertex(d: b2Math.b2Vec2): b2Math.b2Vec2; @@ -2282,71 +2361,75 @@ module Box2D.Collision.Shapes { /** * Cast a ray against this shape. - * @output Ray cast results, this argument is `out`. - * @input Ray cast input parameters. - * @transform The transform to be applied to the shape. + * @param output Ray cast results, this argument is `out`. + * @param input Ray cast input parameters. + * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ - public RayCast(output: b2RayCastOutput, + public RayCast( + output: b2RayCastOutput, input: b2RayCastInput, transform: b2Math.b2Transform): bool; /** * Set the shape values from another shape. - * @other The other shape to copy values from. + * @param other The other shape to copy values from. **/ public Set(other: b2Shape): void; /** * Copy vertices. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. - * @vertices List of vertices to create the polygon shape from. - * @vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. + * @param vertices List of vertices to create the polygon shape from. + * @param vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public SetAsArray(vertices: b2Math.b2Vec2[], vertexCount?: number): void; /** * Build vertices to represent an axis-aligned box. - * @hx The half-width. - * @hy The half-height. + * @param hx The half-width. + * @param hy The half-height. * @return Box polygon shape. **/ public SetAsBox(hx: number, hy: number): void; /** * Creates a single edge from two vertices. - * @v1 First vertex. - * @v2 Second vertex. + * @param v1 First vertex. + * @param v2 Second vertex. * @return Edge polygon shape. **/ public SetAsEdge(v1: b2Math.b2Vec2, b2: b2Math.b2Vec2): void; /** * Build vertices to represent an oriented box. - * @hx The half-width. - * @hy The half-height. - * @center The center of the box in local coordinates, default is null (no center?) - * @angle The rotation of the box in local coordinates, default is 0.0. + * @param hx The half-width. + * @param hy The half-height. + * @param center The center of the box in local coordinates, default is null (no center?) + * @param angle The rotation of the box in local coordinates, default is 0.0. * @return Oriented box shape. **/ public SetAsOrientedBox(hx: number, hy: number, center?: b2Math.b2Vec2, angle?: number): void; /** * This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. - * @vertices List of vertices to create the polygon shape from. - * @vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. + * @param vertices List of vertices to create the polygon shape from. + * @param vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public SetAsVector(vertices: any[], vertexCount?: number): void; /** * Test a point for containment in this shape. This only works for convex shapes. - * @xf Shape world transform. - * @p Point to test against, in world coordinates. + * @param xf Shape world transform. + * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Math.b2Transform, p: b2Math.b2Vec2): bool; } +} + +module Box2D.Collision.Shapes { /** * A shape is used for collision detection. Shapes are created in b2Body. You can use shape for collision detection before they are attached to the world. @@ -2379,27 +2462,28 @@ module Box2D.Collision.Shapes { /** * Creates a new b2Shape. **/ - constructor (); + constructor(); /** * Given a transform, compute the associated axis aligned bounding box for this shape. - * @aabb Calculated AABB, this argument is `out`. - * @xf Transform to calculate the AABB. + * @param aabb Calculated AABB, this argument is `out`. + * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. - * @massData Calculate the mass, this argument is `out`. + * @param massData Calculate the mass, this argument is `out`. + * @param density Density. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane - * @normal The surface normal. - * @offset The surface offset along the normal. - * @xf The shape transform. - * @c The centroid, this argument is `out`. + * @param normal The surface normal. + * @param offset The surface offset along the normal. + * @param xf The shape transform. + * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Math.b2Vec2, @@ -2419,10 +2503,10 @@ module Box2D.Collision.Shapes { /** * Cast a ray against this shape. - * @output Ray cast results, this argument is `out`. - * @input Ray cast input parameters. - * @transform The transform to be applied to the shape. - * @return True if the ray hits the shape, otherwise false. + * @param output Ray cast results, this argument is `out`. + * @param input Ray cast input parameters. + * @param transform The transform to be applied to the shape. + * @param return True if the ray hits the shape, otherwise false. **/ public RayCast( output: b2RayCastOutput, @@ -2431,16 +2515,16 @@ module Box2D.Collision.Shapes { /** * Set the shape values from another shape. - * @other The other shape to copy values from. + * @param other The other shape to copy values from. **/ public Set(other: b2Shape): void; /** * Test if two shapes overlap with the applied transforms. - * @shape1 shape to test for overlap with shape2. - * @transform1 shape1 transform to apply. - * @shape2 shape to test for overlap with shape1. - * @transform2 shape2 transform to apply. + * @param shape1 shape to test for overlap with shape2. + * @param transform1 shape1 transform to apply. + * @param shape2 shape to test for overlap with shape1. + * @param transform2 shape2 transform to apply. * @return True if shape1 and shape2 overlap, otherwise false. **/ public static TestOverlap( @@ -2451,8 +2535,8 @@ module Box2D.Collision.Shapes { /** * Test a point for containment in this shape. This only works for convex shapes. - * @xf Shape world transform. - * @p Point to test against, in world coordinates. + * @param xf Shape world transform. + * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Math.b2Transform, p: b2Math.b2Vec2): bool; @@ -2483,28 +2567,28 @@ module Box2D.Dynamics { /** * Apply a force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the angular velocity. This wakes up the body. - * @force The world force vector, usually in Newtons (N). - * @point The world position of the point of application. + * @param force The world force vector, usually in Newtons (N). + * @param point The world position of the point of application. **/ public ApplyForce(force: b2Math.b2Vec2, point: b2Math.b2Vec2): void; /** * Apply an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of application is not at the center of mass. This wakes up the body. - * @impules The world impulse vector, usually in N-seconds or kg-m/s. - * @point The world position of the point of application. + * @param impules The world impulse vector, usually in N-seconds or kg-m/s. + * @param point The world position of the point of application. **/ public ApplyImpulse(impulse: b2Math.b2Vec2, point: b2Math.b2Vec2): void; /** * Apply a torque. This affects the angular velocity without affecting the linear velocity of the center of mass. This wakes up the body. - * @torque Force applied about the z-axis (out of the screen), usually in N-m. + * @param torque Force applied about the z-axis (out of the screen), usually in N-m. **/ public ApplyTorque(torque: number): void; /** * Creates a fixture and attach it to this body. Use this function if you need to set some fixture parameters, like friction. Otherwise you can create the fixture directly from a shape. If the density is non-zero, this function automatically updates the mass of the body. Contacts are not created until the next time step. * @warning This function is locked during callbacks. - * @def The fixture definition; + * @param def The fixture definition; * @return The created fixture. **/ public CreateFixture(def: b2FixtureDef): b2Fixture; @@ -2512,8 +2596,8 @@ module Box2D.Dynamics { /** * Creates a fixture from a shape and attach it to this body. This is a convenience function. Use b2FixtureDef if you need to set parameters like friction, restitution, user data, or filtering. This function automatically updates the mass of the body. * @warning This function is locked during callbacks. - * @shape The shaped of the fixture (to be cloned). - * @density The shape density, default is 0.0, set to zero for static bodies. + * @param shape The shaped of the fixture (to be cloned). + * @param density The shape density, default is 0.0, set to zero for static bodies. * @return The created fixture. **/ public CreateFixture2(shape: b2Shapes.b2Shape, density?: number): b2Fixture; @@ -2521,7 +2605,7 @@ module Box2D.Dynamics { /** * Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts associated with this fixture. This will automatically adjust the mass of the body if the body is dynamic and the fixture has positive density. All fixtures attached to a body are implicitly destroyed when the body is destroyed. * @warning This function is locked during callbacks. - * @fixture The fixed to be removed. + * @param fixture The fixed to be removed. **/ public DestroyFixture(fixture: b2Fixture): void; @@ -2594,14 +2678,14 @@ module Box2D.Dynamics { /** * Get the world velocity of a local point. - * @localPoint Point in local coordinates. + * @param localPoint Point in local coordinates. * @return The world velocity of the point. **/ public GetLinearVelocityFromLocalPoint(localPoint: b2Math.b2Vec2): b2Math.b2Vec2; /** * Get the world linear velocity of a world point attached to this body. - * @worldPoint Point in world coordinates. + * @param worldPoint Point in world coordinates. * @return The world velocity of the point. **/ public GetLinearVelocityFromWorldPoint(worldPoint: b2Math.b2Vec2): b2Math.b2Vec2; @@ -2614,14 +2698,14 @@ module Box2D.Dynamics { /** * Gets a local point relative to the body's origin given a world point. - * @worldPoint Pointin world coordinates. + * @param worldPoint Pointin world coordinates. * @return The corresponding local point relative to the body's origin. **/ public GetLocalPoint(worldPoint: b2Math.b2Vec2): b2Math.b2Vec2; /** * Gets a local vector given a world vector. - * @worldVector World vector. + * @param worldVector World vector. * @return The corresponding local vector. **/ public GetLocalVector(worldVector: b2Math.b2Vec2): b2Math.b2Vec2; @@ -2634,7 +2718,7 @@ module Box2D.Dynamics { /** * Get the mass data of the body. The rotational inertial is relative to the center of mass. - * @data Body's mass data, this argument is `out`. + * @param data Body's mass data, this argument is `out`. **/ public GetMassData(data: b2Shapes.b2MassData): void; @@ -2682,14 +2766,14 @@ module Box2D.Dynamics { /** * Get the world coordinates of a point given the local coordinates. - * @localPoint Point on the body measured relative to the body's origin. + * @param localPoint Point on the body measured relative to the body's origin. * @return localPoint expressed in world coordinates. **/ public GetWorldPoint(localPoint: b2Math.b2Vec2): b2Math.b2Vec2; /** * Get the world coordinates of a vector given the local coordinates. - * @localVector Vector fixed in the body. + * @param localVector Vector fixed in the body. * @return localVector expressed in world coordinates. **/ public GetWorldVector(localVector: b2Math.b2Vec2): b2Math.b2Vec2; @@ -2737,109 +2821,113 @@ module Box2D.Dynamics { /** * Set the active state of the body. An inactive body is not simulated and cannot be collided with or woken up. If you pass a flag of true, all fixtures will be added to the broad-phase. If you pass a flag of false, all fixtures will be removed from the broad-phase and all contacts will be destroyed. Fixtures and joints are otherwise unaffected. You may continue to create/destroy fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive and will not participate in collisions, ray-casts, or queries. Joints connected to an inactive body are implicitly inactive. An inactive body is still owned by a b2World object and remains in the body list. - * @flag True to activate, false to deactivate. + * @param flag True to activate, false to deactivate. **/ public SetActive(flag: bool): void; /** * Set the world body angle - * @angle New angle of the body. + * @param angle New angle of the body. **/ public SetAngle(angle: number): void; /** * Set the angular damping of the body. - * @angularDamping New angular damping value. + * @param angularDamping New angular damping value. **/ public SetAngularDamping(angularDamping: number): void; /** * Set the angular velocity. - * @omega New angular velocity in radians/second. + * @param omega New angular velocity in radians/second. **/ public SetAngularVelocity(omega: number): void; /** * Set the sleep state of the body. A sleeping body has vety low CPU cost. - * @flag True to set the body to awake, false to put it to sleep. + * @param flag True to set the body to awake, false to put it to sleep. **/ public SetAwake(flag: bool): void; /** * Should this body be treated like a bullet for continuous collision detection? - * @flag True for bullet, false for normal. + * @param flag True for bullet, false for normal. **/ public SetBullet(flag: bool): void; /** * Set this body to have fixed rotation. This causes the mass to be reset. - * @fixed True for no rotation, false to allow for rotation. + * @param fixed True for no rotation, false to allow for rotation. **/ public SetFixedRotation(fixed: bool): void; /** * Set the linear damping of the body. - * @linearDamping The new linear damping for this body. + * @param linearDamping The new linear damping for this body. **/ public SetLinearDamping(linearDamping: number): void; /** * Set the linear velocity of the center of mass. - * @v New linear velocity of the center of mass. + * @param v New linear velocity of the center of mass. **/ public SetLinearVelocity(v: b2Math.b2Vec2): void; /** * Set the mass properties to override the mass properties of the fixtures Note that this changes the center of mass position. Note that creating or destroying fixtures can also alter the mass. This function has no effect if the body isn't dynamic. * @warning The supplied rotational inertia should be relative to the center of mass. - * @massData New mass data properties. + * @param massData New mass data properties. **/ public SetMassData(massData: b2Shapes.b2MassData): void; /** * Set the world body origin position. - * @position New world body origin position. + * @param position New world body origin position. **/ public SetPosition(position: b2Math.b2Vec2): void; /** * Set the position of the body's origin and rotation (radians). This breaks any contacts and wakes the other bodies. - * @position New world body origin position. - * @angle New world rotation angle of the body in radians. + * @param position New world body origin position. + * @param angle New world rotation angle of the body in radians. **/ public SetPositionAndAngle(position: b2Math.b2Vec2, angle: number): void; /** * Is this body allowed to sleep - * @flag True if the body can sleep, false if not. + * @param flag True if the body can sleep, false if not. **/ public SetSleepingAllowed(flag: bool): void; /** * Set the position of the body's origin and rotation (radians). This breaks any contacts and wakes the other bodies. Note this is less efficient than the other overload - you should use that if the angle is available. - * @xf Body's origin and rotation (radians). + * @param xf Body's origin and rotation (radians). **/ public SetTransform(xf: b2Math.b2Transform): void; /** * Set the type of this body. This may alter the mass and velocity - * @type Type enum. + * @param type Type enum. **/ public SetType(type: number): void; /** * Set the user data. Use this to store your application specific data. - * @data The user data for this body. + * @param data The user data for this body. **/ public SetUserData(data: any): void; /** * Splits a body into two, preserving dynamic properties * @note This provides a feature specific to this port. + * @param callback * @return The newly created bodies from the split. **/ public Split(callback: (fixture: b2Fixture) => bool): b2Body; } +} + +module Box2D.Dynamics { /** * A body definition holds all the data needed to construct a rigid body. You can safely re-use body definitions. @@ -2919,6 +3007,9 @@ module Box2D.Dynamics { **/ public userData: any; } +} + +module Box2D.Dynamics { /** * Implement this class to provide collision filtering. In other words, you can implement this class if you want finer control over contact creation. @@ -2930,7 +3021,7 @@ module Box2D.Dynamics { * @note This function is not in the box2dweb.as code -- might not work. * @see b2World.Raycast() * @see b2ContactFilter.ShouldCollide() - * @userData User provided data. Comments indicate that this might be a b2Fixture. + * @param userData User provided data. Comments indicate that this might be a b2Fixture. * @return True if the fixture should be considered for ray intersection, otherwise false. **/ public RayCollide(userData: any): bool; @@ -2938,12 +3029,15 @@ module Box2D.Dynamics { /** * Return true if contact calculations should be performed between these two fixtures. * @warning For performance reasons this is only called when the AABBs begin to overlap. - * @fixtureA b2Fixture potentially colliding with fixtureB. - * @fixtureB b2Fixture potentially colliding with fixtureA. + * @param fixtureA b2Fixture potentially colliding with fixtureB. + * @param fixtureB b2Fixture potentially colliding with fixtureA. * @return True if fixtureA and fixtureB probably collide requiring more calculations, otherwise false. **/ public ShouldCollide(fixtureA: b2Fixture, fixtureB: b2Fixture): bool; } +} + +module Box2D.Dynamics { /** * Contact impulses for reporting. Impulses are used instead of forces because sub-step forces may approach infinity for rigid body collisions. These match up one-to-one with the contact points in b2Manifold. @@ -2960,6 +3054,9 @@ module Box2D.Dynamics { **/ public tangentImpulses: b2Math.b2Vec2; } +} + +module Box2D.Dynamics { /** * Implement this class to get contact information. You can use these results for things like sounds and game logic. You can also get contact results by traversing the contact lists after the time step. However, you might miss some contacts because continuous physics leads to sub-stepping. Additionally you may receive multiple callbacks for the same contact in a single time step. You should strive to make your callbacks efficient because there may be many callbacks per time step. @@ -2969,30 +3066,33 @@ module Box2D.Dynamics { /** * Called when two fixtures begin to touch. - * @contact Contact point. + * @param contact Contact point. **/ public BeginContact(contact: Contacts.b2Contact): void; /** * Called when two fixtures cease to touch. - * @contact Contact point. + * @param contact Contact point. **/ public EndContact(contact: Contacts.b2Contact): void; /** * This lets you inspect a contact after the solver is finished. This is useful for inspecting impulses. Note: the contact manifold does not include time of impact impulses, which can be arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly in a separate data structure. Note: this is only called for contacts that are touching, solid, and awake. - * @contact Contact point. - * @impulse Contact impulse. + * @param contact Contact point. + * @param impulse Contact impulse. **/ public PostSolve(contact: Contacts.b2Contact, impulse: b2ContactImpulse): void; /** * This is called after a contact is updated. This allows you to inspect a contact before it goes to the solver. If you are careful, you can modify the contact manifold (e.g. disable contact). A copy of the old manifold is provided so that you can detect changes. Note: this is called only for awake bodies. Note: this is called even when the number of contact points is zero. Note: this is not called for sensors. Note: if you set the number of contact points to zero, you will not get an EndContact callback. However, you may get a BeginContact callback the next step. - * @contact Contact point. - * @oldManifold Old manifold. + * @param contact Contact point. + * @param oldManifold Old manifold. **/ public PreSolve(contact: Contacts.b2Contact, oldManifold: b2Collision.b2Manifold): void; } +} + +module Box2D.Dynamics { /** * Implement and register this class with a b2World to provide debug drawing of physics entities in your game. @@ -3040,60 +3140,60 @@ module Box2D.Dynamics { /** * Append flags to the current flags. - * @flags Flags to add. + * @param flags Flags to add. **/ - public AppendFlags(flags:number): void; + public AppendFlags(flags: number): void; /** * Clear flags from the current flags. - * @flags flags to clear. + * @param flags flags to clear. **/ - public ClearFlags(flags:number): void; + public ClearFlags(flags: number): void; /** * Draw a circle. - * @center Circle center point. - * @radius Circle radius. - * @color Circle draw color. + * @param center Circle center point. + * @param radius Circle radius. + * @param color Circle draw color. **/ public DrawCircle(center: b2Math.b2Vec2, radius: number, color: b2Common.b2Color): void; /** * Draw a closed polygon provided in CCW order. - * @vertices Polygon verticies. - * @vertexCount Number of vertices in the polygon, usually vertices.length. - * @color Polygon draw color. + * @param vertices Polygon verticies. + * @param vertexCount Number of vertices in the polygon, usually vertices.length. + * @param color Polygon draw color. **/ - public DrawPolygon(vertices: b2Math.b2Vec2[], vertexCount:number, color: b2Common.b2Color): void; + public DrawPolygon(vertices: b2Math.b2Vec2[], vertexCount: number, color: b2Common.b2Color): void; /** * Draw a line segment. - * @p1 Line beginpoint. - * @p2 Line endpoint. - * @color Line color. + * @param p1 Line beginpoint. + * @param p2 Line endpoint. + * @param color Line color. **/ public DrawSegment(p1: b2Math.b2Vec2, p2: b2Math.b2Vec2, color: b2Common.b2Color): void; /** * Draw a solid circle. - * @center Circle center point. - * @radius Circle radius. - * @axis Circle axis. - * @color Circle color. + * @param center Circle center point. + * @param radius Circle radius. + * @param axis Circle axis. + * @param color Circle color. **/ public DrawSolidCircle(center: b2Math.b2Vec2, radius: number, axis: b2Math.b2Vec2, color: b2Common.b2Color): void; /** * Draw a solid closed polygon provided in CCW order. - * @vertices Polygon verticies. - * @vertexCount Number of vertices in the polygon, usually vertices.length. - * @color Polygon draw color. + * @param vertices Polygon verticies. + * @param vertexCount Number of vertices in the polygon, usually vertices.length. + * @param color Polygon draw color. **/ - public DrawSolidPolygon(vertices: b2Math.b2Vec2[], vertexCount:number, color: b2Common.b2Color): void; + public DrawSolidPolygon(vertices: b2Math.b2Vec2[], vertexCount: number, color: b2Common.b2Color): void; /** * Draw a transform. Choose your own length scale. - * @xf Transform to draw. + * @param xf Transform to draw. **/ public DrawTransform(xf: b2Math.b2Transform): void; @@ -3142,47 +3242,50 @@ module Box2D.Dynamics { /** * Set the alpha value used for lines. - * @alpha Alpha value for drawing lines. + * @param alpha Alpha value for drawing lines. **/ public SetAlpha(alpha: number): void; /** * Set the draw scale. - * @drawScale Draw scale ratio. + * @param drawScale Draw scale ratio. **/ public SetDrawScale(drawScale: number): void; /** * Set the alpha value used for fills. - * @alpha Alpha value for drawing fills. + * @param alpha Alpha value for drawing fills. **/ public SetFillAlpha(alpha: number): void; /** * Set the drawing flags. - * @flags Sets the drawing flags. + * @param flags Sets the drawing flags. **/ public SetFlags(flags: number): void; /** * Set the line thickness. - * @lineThickness The new line thickness. + * @param lineThickness The new line thickness. **/ public SetLineThickness(lineThickness: number): void; /** * Set the HTML Canvas Element for drawing. * @note box2dflash uses Sprite object, box2dweb uses CanvasRenderingContext2D, that is why this function is called SetSprite(). - * @canvas HTML Canvas Element to draw debug information to. + * @param canvas HTML Canvas Element to draw debug information to. **/ public SetSprite(canvas: CanvasRenderingContext2D): void; /** * Set the scale used for drawing XForms. - * @xformScale The transform scale. + * @param xformScale The transform scale. **/ public SetXFormScale(xformScale: number): void; } +} + +module Box2D.Dynamics { /** * Joints and shapes are destroyed when their associated body is destroyed. Implement this listener so that you may nullify references to these joints and shapes. @@ -3191,22 +3294,25 @@ module Box2D.Dynamics { /** * Called when any fixture is about to be destroyed due to the destruction of its parent body. - * @fixture b2Fixture being destroyed. + * @param fixture b2Fixture being destroyed. **/ public SayGoodbyeFixture(fixture: b2Fixture): void; /** * Called when any joint is about to be destroyed due to the destruction of one of its attached bodies. - * @joint b2Joint being destroyed. + * @param joint b2Joint being destroyed. **/ public SayGoodbyeJoint(joint: Joints.b2Joint): void; } +} + +module Box2D.Dynamics { /** * This holds contact filtering data. **/ export class b2FilterData { - + /** * The collision category bits. Normally you would just set one bit. **/ @@ -3228,6 +3334,9 @@ module Box2D.Dynamics { **/ public Copy(): b2FilterData; } +} + +module Box2D.Dynamics { /** * A fixture is used to attach a shape to a body for collision detection. A fixture inherits its transform from its parent. Fixtures hold additional non-geometric data such as friction, collision filters, etc. Fixtures are created via b2Body::CreateFixture. @@ -3267,7 +3376,7 @@ module Box2D.Dynamics { /** * Get the mass data for this fixture. The mass data is based on the density and the shape. The rotational inertia is about the shape's origin. This operation may be expensive. - * @massData This is a reference to a valid b2MassData, if it is null a new b2MassData is allocated and then returned. Default = null. + * @param massData This is a reference to a valid b2MassData, if it is null a new b2MassData is allocated and then returned. Default = null. * @return Mass data. **/ public GetMassData(massData?: b2Shapes.b2MassData): b2Shapes.b2MassData; @@ -3310,55 +3419,58 @@ module Box2D.Dynamics { /** * Perform a ray cast against this shape. - * @output Ray cast results. This argument is out. - * @input Ray cast input parameters. + * @param output Ray cast results. This argument is out. + * @param input Ray cast input parameters. * @return True if the ray hits the shape, otherwise false. **/ public RayCast(output: b2Collision.b2RayCastOutput, input: b2Collision.b2RayCastInput): bool; /** * Set the density of this fixture. This will _not_ automatically adjust the mass of the body. You must call b2Body::ResetMassData to update the body's mass. - * @density The new density. + * @param density The new density. **/ public SetDensity(density: number): void; /** * Set the contact filtering data. This will not update contacts until the next time step when either parent body is active and awake. - * @filter The new filter data. + * @param filter The new filter data. **/ public SetFilterData(filter: any): void; /** * Set the coefficient of friction. - * @friction The new friction coefficient. + * @param friction The new friction coefficient. **/ public SetFriction(friction: number): void; /** * Get the coefficient of restitution. - * @resitution The new restitution coefficient. + * @param resitution The new restitution coefficient. **/ public SetRestitution(restitution: number): void; /** * Set if this fixture is a sensor. - * @sensor True to set as a sensor, false to not be a sensor. + * @param sensor True to set as a sensor, false to not be a sensor. **/ public SetSensor(sensor: bool): void; /** * Set the user data. Use this to store your application specific data. - * @data User provided data. + * @param data User provided data. **/ public SetUserData(data: any): void; /** * Test a point for containment in this fixture. - * @p Point to test against, in world coordinates. + * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(p: b2Math.b2Vec2): bool; } +} + +module Box2D.Dynamics { /** * A fixture definition is used to create a fixture. This class defines an abstract fixture definition. You can reuse fixture definitions safely. @@ -3405,12 +3517,15 @@ module Box2D.Dynamics { **/ constructor(); } +} + +module Box2D.Dynamics { /** * The world class manages all physics entities, dynamic simulation, and asynchronous queries. **/ export class b2World { - + /** * Locked **/ @@ -3423,14 +3538,14 @@ module Box2D.Dynamics { /** * Creates a new world. - * @gravity The world gravity vector. - * @doSleep Improvie performance by not simulating inactive bodies. + * @param gravity The world gravity vector. + * @param doSleep Improvie performance by not simulating inactive bodies. **/ constructor(gravity: b2Math.b2Vec2, doSleep: bool); /** * Add a controller to the world list. - * @c Controller to add. + * @param c Controller to add. * @return Controller that was added to the world. **/ public AddController(c: Controllers.b2Controller): Controllers.b2Controller; @@ -3442,14 +3557,14 @@ module Box2D.Dynamics { /** * Create a rigid body given a definition. No reference to the definition is retained. - * @def Body's definition. + * @param def Body's definition. * @return Created rigid body. **/ public CreateBody(def: b2BodyDef): b2Body; /** * Creates a new controller. - * @controller New controller. + * @param controller New controller. * @return New controller. **/ public CreateController(controller: Controllers.b2Controller): Controllers.b2Controller; @@ -3457,14 +3572,14 @@ module Box2D.Dynamics { /** * Create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies to cease colliding. * @warning This function is locked during callbacks. - * @def Joint definition. + * @param def Joint definition. * @return New created joint. **/ public CreateJoint(def: Joints.b2JointDef): Joints.b2Joint; /** * Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during callbacks. - * @b Body to destroy. + * @param b Body to destroy. * @warning This function is locked during callbacks. **/ public DestroyBody(b: b2Body): void; @@ -3472,13 +3587,13 @@ module Box2D.Dynamics { /** * Destroy a controller given the controller instance. * @warning This function is locked during callbacks. - * @controller Controller to destroy. + * @param controller Controller to destroy. **/ public DestroyController(controller: Controllers.b2Controller): void; /** * Destroy a joint. This may cause the connected bodies to begin colliding. - * @j Joint to destroy. + * @param j Joint to destroy. **/ public DestroyJoint(j: Joints.b2Joint): void; @@ -3549,31 +3664,31 @@ module Box2D.Dynamics { /** * Query the world for all fixtures that potentially overlap the provided AABB. - * @callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. - * @aabb The query bounding box. + * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. + * @param aabb The query bounding box. **/ public QueryAABB(callback: (fixutre: b2Fixture) => bool, aabb: b2Collision.b2AABB): void; /** * Query the world for all fixtures that contain a point. * @note This provides a feature specific to this port. - * @callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. - * @p The query point. + * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. + * @param p The query point. **/ public QueryPoint(callback: (fixture: b2Fixture) => bool, p: b2Math.b2Vec2): void; /** * Query the world for all fixtures that precisely overlap the provided transformed shape. * @note This provides a feature specific to this port. - * @callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. - * @shape The query shape. - * @transform Optional transform, default = null. + * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. + * @param shape The query shape. + * @param transform Optional transform, default = null. **/ public QueryShape(callback: (fixture: b2Fixture) => bool, shape: b2Shapes.b2Shape, transform?: b2Math.b2Transform): void; /** * Ray-cast the world for all fixtures in the path of the ray. Your callback Controls whether you get the closest point, any point, or n-points The ray-cast ignores shapes that contain the starting point. - * @callback A callback function which must be of signature: + * @param callback A callback function which must be of signature: * function Callback( * fixture:b2Fixture, // The fixture hit by the ray * point:b2Vec2, // The point of initial intersection @@ -3581,87 +3696,87 @@ module Box2D.Dynamics { * fraction:Number // The fractional length along the ray of the intersection * ):Number * Callback should return the new length of the ray as a fraction of the original length. By returning 0, you immediately terminate. By returning 1, you continue wiht the original ray. By returning the current fraction, you proceed to find the closest point. - * @point1 The ray starting point. - * @point2 The ray ending point. + * @param point1 The ray starting point. + * @param point2 The ray ending point. **/ public RayCast(callback: (fixture: b2Fixture, point: b2Math.b2Vec2, normal: b2Math.b2Vec2, fraction: number) => number, point1: b2Math.b2Vec2, point2: b2Math.b2Vec2): void; /** * Ray-cast the world for all fixture in the path of the ray. - * @point1 The ray starting point. - * @point2 The ray ending point. + * @param point1 The ray starting point. + * @param point2 The ray ending point. * @return Array of all the fixtures intersected by the ray. **/ public RayCastAll(point1: b2Math.b2Vec2, point2: b2Math.b2Vec2): b2Fixture[]; /** * Ray-cast the world for the first fixture in the path of the ray. - * @point1 The ray starting point. - * @point2 The ray ending point. + * @param point1 The ray starting point. + * @param point2 The ray ending point. * @return First fixture intersected by the ray. **/ public RayCastOne(point1: b2Math.b2Vec2, point2: b2Math.b2Vec2): b2Fixture; /** * Removes the controller from the world. - * @c Controller to remove. + * @param c Controller to remove. **/ public RemoveController(c: Controllers.b2Controller): void; /** * Use the given object as a broadphase. The old broadphase will not be cleanly emptied. * @warning This function is locked during callbacks. - * @broadphase: Broad phase implementation. + * @param broadphase: Broad phase implementation. **/ public SetBroadPhase(broadPhase: b2Collision.IBroadPhase): void; /** * Register a contact filter to provide specific control over collision. Otherwise the default filter is used (b2_defaultFilter). - * @filter Contact filter'er. + * @param filter Contact filter'er. **/ public SetContactFilter(filter: b2ContactFilter): void; /** * Register a contact event listener. - * @listener Contact event listener. + * @param listener Contact event listener. **/ public SetContactListener(listener: b2ContactListener): void; /** * Enable/disable continuous physics. For testing. - * @flag True for continuous physics, otherwise false. + * @param flag True for continuous physics, otherwise false. **/ public SetContinuousPhysics(flag: bool): void; /** * Register a routine for debug drawing. The debug draw functions are called inside the b2World::Step method, so make sure your renderer is ready to consume draw commands when you call Step(). - * @debugDraw Debug drawing instance. + * @param debugDraw Debug drawing instance. **/ public SetDebugDraw(debugDraw: b2DebugDraw): void; - + /** * Destruct the world. All physics entities are destroyed and all heap memory is released. - * @listener Destruction listener instance. + * @param listener Destruction listener instance. **/ public SetDestructionListener(listener: b2DestructionListener): void; /** * Change the global gravity vector. - * @gravity New global gravity vector. + * @param gravity New global gravity vector. **/ public SetGravity(gravity: b2Math.b2Vec2): void; /** * Enable/disable warm starting. For testing. - * @flag True for warm starting, otherwise false. + * @param flag True for warm starting, otherwise false. **/ public SetWarmStarting(flag: bool): void; /** * Take a time step. This performs collision detection, integration, and constraint solution. - * @dt The amout of time to simulate, this should not vary. - * @velocityIterations For the velocity constraint solver. - * @positionIterations For the position constraint solver. + * @param dt The amout of time to simulate, this should not vary. + * @param velocityIterations For the velocity constraint solver. + * @param positionIterations For the position constraint solver. **/ public Step(dt: number, velocityIterations: number, positionIterations: number): void; @@ -3683,78 +3798,82 @@ module Box2D.Dynamics.Contacts { * Constructor **/ constructor(); - + /** * Flag this contact for filtering. Filtering will occur the next time step. **/ public FlagForFiltering(): void; - + /** * Get the first fixture in this contact. * @return First fixture in this contact. **/ public GetFixtureA(): b2Fixture; - + /** * Get the second fixture in this contact. * @return Second fixture in this contact. **/ public GetFixtureB(): b2Fixture; - + /** * Get the contact manifold. Do not modify the manifold unless you understand the internals of Box2D. * @return Contact manifold. **/ public GetManifold(): b2Collision.b2Manifold; - + /** * Get the next contact in the world's contact list. * @return Next contact in the world's contact list. **/ public GetNext(): b2Contact; - + /** * Get the world manifold. + * @param worldManifold World manifold out. * @return World manifold. **/ public GetWorldManifold(worldManifold: b2Collision.b2WorldManifold): void; - + /** * Does this contact generate TOI events for continuous simulation. * @return True for continous, otherwise false. **/ public IsContinuous(): bool; - + /** * Has this contact been disabled? * @return True if disabled, otherwise false. **/ public IsEnabled(): bool; - + /** * Is this contact a sensor? * @return True if sensor, otherwise false. **/ public IsSensor(): bool; - + /** * Is this contact touching. * @return True if contact is touching, otherwise false. **/ public IsTouching(): bool; - + /** * Enable/disable this contact. This can be used inside the pre-solve contact listener. The contact is only disabled for the current time step (or sub-step in continuous collision). - * @flag True to enable, false to disable. + * @param flag True to enable, false to disable. **/ public SetEnabled(flag: bool): void; /** * Change this to be a sensor or-non-sensor contact. - * @sensor True to be sensor, false to not be a sensor. + * @param sensor True to be sensor, false to not be a sensor. **/ public SetSensor(sensor: bool): void; } +} + +module Box2D.Dynamics.Contacts { /** * A contact edge is used to connect bodies and contacts together in a contact graph where each body is a node and each contact is an edge. A contact edge belongs to a doubly linked list maintained in each attached body. Each contact has two contact nodes, one for each attached body. @@ -3781,6 +3900,9 @@ module Box2D.Dynamics.Contacts { **/ public prev: b2ContactEdge; } +} + +module Box2D.Dynamics.Contacts { /** * This structure is used to report contact point results. @@ -3822,9 +3944,111 @@ module Box2D.Dynamics.Contacts { **/ public tangentImpulse: number; } +} +module Box2D.Dynamics.Controllers { + /** + * Base class for controllers. Controllers are a convience for encapsulating common per-step functionality. + **/ + export class b2Controller { + /** + * Body count. + **/ + public m_bodyCount: number; + + /** + * List of bodies. + **/ + public m_bodyList: b2ControllerEdge; + + /** + * Adds a body to the controller. + * @param body Body to add. + **/ + public AddBody(body: b2Body): void; + + /** + * Removes all bodies from the controller. + **/ + public Clear(): void; + + /** + * Debug drawing. + * @param debugDraw Handle to drawer. + **/ + public Draw(debugDraw: b2DebugDraw): void; + + /** + * Gets the body list. + * @return Body list. + **/ + public GetBodyList(): b2ControllerEdge; + + /** + * Gets the next controller. + * @return Next controller. + **/ + public GetNext(): b2Controller; + + /** + * Gets the world. + * @return World. + **/ + public GetWorld(): b2World; + + /** + * Removes a body from the controller. + * @param body Body to remove from this controller. + **/ + public RemoveBody(body: b2Body): void; + + /** + * Step + * @param step b2TimeStep -> Private internal class. Not sure why this is exposed. + **/ + public Step(step: any/*b2TimeStep*/): void; + } +} + +module Box2D.Dynamics.Controllers { + + /** + * Controller Edge. + **/ + export class b2ControllerEdge { + + /** + * Body. + **/ + public body: b2Body; + + /** + * Provides quick access to the other end of this edge. + **/ + public controller: b2Controller; + + /** + * The next controller edge in the controller's body list. + **/ + public nextBody: b2ControllerEdge; + + /** + * The next controller edge in the body's controller list. + **/ + public nextController: b2ControllerEdge; + + /** + * The previous controller edge in the controller's body list. + **/ + public prevBody: b2ControllerEdge; + + /** + * The previous controller edge in the body's controller list. + **/ + public prevController: b2ControllerEdge; + } } module Box2D.Dynamics.Controllers { @@ -3886,6 +4110,9 @@ module Box2D.Dynamics.Controllers { **/ public velocity: b2Math.b2Vec2; } +} + +module Box2D.Dynamics.Controllers { /** * Applies an acceleration every frame, like gravity @@ -3898,11 +4125,13 @@ module Box2D.Dynamics.Controllers { public A: b2Math.b2Vec2; /** - * Step. - * @step Internal b2TimeStep structure. + * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } +} + +module Box2D.Dynamics.Controllers { /** * Applies an acceleration every frame, like gravity. @@ -3915,110 +4144,13 @@ module Box2D.Dynamics.Controllers { public A: b2Math.b2Vec2; /** - * Step. - * @step Internal b2TimeStep structure. + * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } +} - /** - * Base class for controllers. Controllers are a convience for encapsulating common per-step functionality. - **/ - export class b2Controller { - - /** - * Body count. - **/ - public m_bodyCount: number; - - /** - * List of bodies. - **/ - public m_bodyList: b2ControllerEdge; - - /** - * Adds a body to the controller. - * @body Body to add. - **/ - public AddBody(body: b2Body): void; - - /** - * Removes all bodies from the controller. - **/ - public Clear(): void; - - /** - * Debug drawing. - * @debugDraw Handle to drawer. - **/ - public Draw(debugDraw: b2DebugDraw): void; - - /** - * Gets the body list. - * @return Body list. - **/ - public GetBodyList(): b2ControllerEdge; - - /** - * Gets the next controller. - * @return Next controller. - **/ - public GetNext(): b2Controller; - - /** - * Gets the world. - * @return World. - **/ - public GetWorld(): b2World; - - /** - * Removes a body from the controller. - * @body Body to remove from this controller. - **/ - public RemoveBody(body: b2Body): void; - - /** - * Step - * @step b2TimeStep -> Private internal class. Not sure why this is exposed. - **/ - public Step(step: any/*b2TimeStep*/): void; - } - - /** - * Controller Edge. - **/ - export class b2ControllerEdge { - - /** - * Body. - **/ - public body: b2Body; - - /** - * Provides quick access to the other end of this edge. - **/ - public controller: b2Controller; - - /** - * The next controller edge in the controller's body list. - **/ - public nextBody: b2ControllerEdge; - - /** - * The next controller edge in the body's controller list. - **/ - public nextController: b2ControllerEdge; - - /** - * The previous controller edge in the controller's body list. - **/ - public prevBody: b2ControllerEdge; - - /** - * The previous controller edge in the body's controller list. - **/ - public prevController: b2ControllerEdge; - } +module Box2D.Dynamics.Controllers { /** * Applies simplified gravity between every pair of bodies. @@ -4037,11 +4169,13 @@ module Box2D.Dynamics.Controllers { public invSqr: bool; /** - * Step. - * @step Internal b2TimeStep structure. + * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } +} + +module Box2D.Dynamics.Controllers { /** * Applies top down linear damping to the controlled bodies The damping is calculated by multiplying velocity by a matrix in local co-ordinates. @@ -4061,19 +4195,163 @@ module Box2D.Dynamics.Controllers { /** * Helper function to set T in a common case. - * @xDamping x - * @yDamping y + * @param xDamping x + * @param yDamping y **/ public SetAxisAligned(xDamping: number, yDamping: number): void; /** - * Step. - * @step Internal b2TimeStep structure. + * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } } +module Box2D.Dynamics.Joints { + + /** + * The base joint class. Joints are used to constraint two bodies together in various fashions. Some joints also feature limits and motors. + **/ + export class b2Joint { + + /** + * Get the anchor point on bodyA in world coordinates. + * @return Anchor A point. + **/ + public GetAnchorA(): b2Math.b2Vec2; + + /** + * Get the anchor point on bodyB in world coordinates. + * @return Anchor B point. + **/ + public GetAnchorB(): b2Math.b2Vec2; + + /** + * Get the first body attached to this joint. + * @return Body A. + **/ + public GetBodyA(): b2Body; + + /** + * Get the second body attached to this joint. + * @return Body B. + **/ + public GetBodyB(): b2Body; + + /** + * Get the next joint the world joint list. + * @return Next joint. + **/ + public GetNext(): b2Joint; + + /** + * Get the reaction force on body2 at the joint anchor in Newtons. + * @param inv_dt + * @return Reaction force (N) + **/ + public GetReactionForce(inv_dt: number): b2Math.b2Vec2; + + /** + * Get the reaction torque on body2 in N. + * @param inv_dt + * @return Reaction torque (N). + **/ + public GetReactionTorque(inv_dt: number): number; + + /** + * Get the type of the concrete joint. + * @return Joint type. + **/ + public GetType(): number; + + /** + * Get the user data pointer. + * @return User data. Cast to your data type. + **/ + public GetUserData(): any; + + /** + * Short-cut function to determine if either body is inactive. + * @return True if active, otherwise false. + **/ + public IsActive(): bool; + + /** + * Set the user data pointer. + * @param data Your custom data. + **/ + public SetUserData(data: any); void; + } +} + +module Box2D.Dynamics.Joints { + + /** + * Joint definitions are used to construct joints. + **/ + export class b2JointDef { + + /** + * The first attached body. + **/ + public bodyA: b2Body; + + /** + * The second attached body. + **/ + public bodyB: b2Body; + + /** + * Set this flag to true if the attached bodies should collide. + **/ + public collideConnected: bool; + + /** + * The joint type is set automatically for concrete joint types. + **/ + public type: number; + + /** + * Use this to attach application specific data to your joints. + **/ + public userData: any; + + /** + * Constructor. + **/ + constructor(); + } +} + +module Box2D.Dynamics.Joints { + + /** + * A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an edge. A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for each attached body. + **/ + export class b2JointEdge { + + /** + * The joint. + **/ + public joint: b2Joint; + + /** + * The next joint edge in the body's joint list. + **/ + public next: b2JointEdge; + + /** + * Provides quick access to the other body attached. + **/ + public other: b2Body; + + /** + * The previous joint edge in the body's joint list. + **/ + public prev: b2JointEdge; + } +} + module Box2D.Dynamics.Joints { /** @@ -4113,35 +4391,39 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Sets the damping ratio. - * @ratio New damping ratio. + * @param ratio New damping ratio. **/ public SetDampingRatio(ratio: number): void; /** * Sets the frequency. - * @hz New frequency (hertz). + * @param hz New frequency (hertz). **/ public SetFrequency(hz: number): void; /** * Sets the length of distance between the two bodies. - * @length New length. + * @param length New length. **/ public SetLength(length: number): void; } +} + +module Box2D.Dynamics.Joints { /** * Distance joint definition. This requires defining an anchor point on both bodies and the non-zero length of the distance joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when saving and loading a game. @@ -4178,16 +4460,19 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, anchors, and length using the world anchors. - * @bA Body A. - * @bB Body B. - * @anchorA Anchor A. - * @anchorB Anchor B. + * @param bA Body A. + * @param bB Body B. + * @param anchorA Anchor A. + * @param anchorB Anchor B. **/ public Initialize(bA: b2Body, bB: b2Body, anchorA: b2Math.b2Vec2, anchorB: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * Friction joint. This is used for top-down friction. It provides 2D translational friction and angular friction. @@ -4230,7 +4515,7 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; @@ -4243,16 +4528,19 @@ module Box2D.Dynamics.Joints { /** * Sets the max force. - * @force New max force. + * @param force New max force. **/ public SetMaxForce(force: number): void; /** * Sets the max torque. - * @torque New max torque. + * @param torque New max torque. **/ public SetMaxTorque(torque: number): void; } +} + +module Box2D.Dynamics.Joints { /** * Friction joint defintion. @@ -4283,15 +4571,18 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. - * @bA Body A. - * @bB Body B. - * @anchor World anchor. + * @param bA Body A. + * @param bB Body B. + * @param anchor World anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic joint. You specify a gear ratio to bind the motions together: coordinate1 + ratio coordinate2 = constant The ratio can be negative or positive. If one joint is a revolute joint and the other joint is a prismatic joint, then the ratio will have units of length or units of 1/length. @@ -4319,23 +4610,27 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Set the gear ratio. - * @force New gear ratio. + * @param force New gear ratio. **/ public SetRatio(ratio: number): void; } +} + +module Box2D.Dynamics.Joints { /** * Gear joint definition. This definition requires two existing revolute or prismatic joints (any combination will work). The provided joints must attach a dynamic body to a static body. @@ -4362,142 +4657,9 @@ module Box2D.Dynamics.Joints { **/ constructor(); } +} - /** - * The base joint class. Joints are used to constraint two bodies together in various fashions. Some joints also feature limits and motors. - **/ - export class b2Joint { - - /** - * Get the anchor point on bodyA in world coordinates. - * @return Anchor A point. - **/ - public GetAnchorA(): b2Math.b2Vec2; - - /** - * Get the anchor point on bodyB in world coordinates. - * @return Anchor B point. - **/ - public GetAnchorB(): b2Math.b2Vec2; - - /** - * Get the first body attached to this joint. - * @return Body A. - **/ - public GetBodyA(): b2Body; - - /** - * Get the second body attached to this joint. - * @return Body B. - **/ - public GetBodyB(): b2Body; - - /** - * Get the next joint the world joint list. - * @return Next joint. - **/ - public GetNext(): b2Joint; - - /** - * Get the reaction force on body2 at the joint anchor in Newtons. - * @inv_dt - * @return Reaction force (N) - **/ - public GetReactionForce(inv_dt: number): b2Math.b2Vec2; - - /** - * Get the reaction torque on body2 in N. - * @inv_dt - * @return Reaction torque (N). - **/ - public GetReactionTorque(inv_dt: number): number; - - /** - * Get the type of the concrete joint. - * @return Joint type. - **/ - public GetType(): number; - - /** - * Get the user data pointer. - * @return User data. Cast to your data type. - **/ - public GetUserData(): any; - - /** - * Short-cut function to determine if either body is inactive. - * @return True if active, otherwise false. - **/ - public IsActive(): bool; - - /** - * Set the user data pointer. - * @data Your custom data. - **/ - public SetUserData(data: any); void; - } - - /** - * Joint definitions are used to construct joints. - **/ - export class b2JointDef { - - /** - * The first attached body. - **/ - public bodyA: b2Body; - - /** - * The second attached body. - **/ - public bodyB: b2Body; - - /** - * Set this flag to true if the attached bodies should collide. - **/ - public collideConnected: bool; - - /** - * The joint type is set automatically for concrete joint types. - **/ - public type: number; - - /** - * Use this to attach application specific data to your joints. - **/ - public userData: any; - - /** - * Constructor. - **/ - constructor(); - } - - /** - * A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an edge. A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for each attached body. - **/ - export class b2JointEdge { - - /** - * The joint. - **/ - public joint: b2Joint; - - /** - * The next joint edge in the body's joint list. - **/ - public next: b2JointEdge; - - /** - * Provides quick access to the other body attached. - **/ - public other: b2Body; - - /** - * The previous joint edge in the body's joint list. - **/ - public prev: b2JointEdge; - } +module Box2D.Dynamics.Joints { /** * A line joint. This joint provides one degree of freedom: translation along an axis fixed in body1. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction. @@ -4506,13 +4668,13 @@ module Box2D.Dynamics.Joints { /** * Enable/disable the joint limit. - * @flag True to enable, false to disable limits + * @param flag True to enable, false to disable limits **/ public EnableLimit(flag: bool): void; /** * Enable/disable the joint motor. - * @flag True to enable, false to disable the motor. + * @param flag True to enable, false to disable the motor. **/ public EnableMotor(flag: bool): void; @@ -4566,13 +4728,14 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; @@ -4597,23 +4760,26 @@ module Box2D.Dynamics.Joints { /** * Set the joint limits, usually in meters. - * @lower Lower limit. - * @upper Upper limit. + * @param lower Lower limit. + * @param upper Upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor force, usually in N. - * @force New max motor force. + * @param force New max motor force. **/ public SetMaxMotorForce(force: number): void; /** * Set the motor speed, usually in meters per second. - * @speed New motor speed. + * @param speed New motor speed. **/ public SetMotorSpeed(speed: number): void; } +} + +module Box2D.Dynamics.Joints { /** * Line joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game. @@ -4669,16 +4835,19 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, anchors, and length using the world anchors. - * @bA Body A. - * @bB Body B. - * @anchor Anchor. - * @axis Axis. + * @param bA Body A. + * @param bB Body B. + * @param anchor Anchor. + * @param axis Axis. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Math.b2Vec2, axis: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces. Note: this joint is not fully documented as it is intended primarily for the testbed. See that for more instructions. @@ -4717,13 +4886,14 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; @@ -4736,28 +4906,31 @@ module Box2D.Dynamics.Joints { /** * Sets the damping ratio. - * @ratio New damping ratio. + * @param ratio New damping ratio. **/ public SetDampingRatio(ratio: number): void; /** * Sets the frequency. - * @hz New frequency (hertz). + * @param hz New frequency (hertz). **/ public SetFrequency(hz: number): void; /** * Sets the max force. - * @maxForce New max force. + * @param maxForce New max force. **/ public SetMaxForce(maxForce: number): void; /** * Use this to update the target point. - * @target New target. + * @param target New target. **/ public SetTarget(target: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * Mouse joint definition. This requires a world target point, tuning parameters, and the time step. @@ -4784,6 +4957,9 @@ module Box2D.Dynamics.Joints { **/ constructor(); } +} + +module Box2D.Dynamics.Joints { /** * A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in body1. Relative rotation is prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction. @@ -4792,13 +4968,13 @@ module Box2D.Dynamics.Joints { /** * Enable/disable the joint limit. - * @flag True to enable, false to disable. + * @param flag True to enable, false to disable. **/ public EnableLimit(flag: bool): void; /** * Enable/disable the joint motor. - * @flag True to enable, false to disable. + * @param flag True to enable, false to disable. **/ public EnableMotor(flag: bool): void; @@ -4846,13 +5022,14 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; @@ -4877,23 +5054,26 @@ module Box2D.Dynamics.Joints { /** * Set the joint limits, usually in meters. - * @lower Lower limit. - * @upper Upper limit. + * @param lower Lower limit. + * @param upper Upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor force, usually in N. - * @force New max force. + * @param force New max force. **/ public SetMaxMotorForce(force: number): void; /** * Set the motor speed, usually in meters per second. - * @speed New motor speed. + * @param speed New motor speed. **/ public SetMotorSpeed(speed: number): void; } +} + +module Box2D.Dynamics.Joints { /** * Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game. @@ -4954,16 +5134,19 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the joint. - * @bA Body A. - * @bB Body B. - * @anchor Anchor. - * @axis Axis. + * @param bA Body A. + * @param bB Body B. + * @param anchor Anchor. + * @param axis Axis. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Math.b2Vec2, axis: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on both sides. This is useful to prevent one side of the pulley hitting the top. @@ -5009,17 +5192,21 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; } +} + +module Box2D.Dynamics.Joints { /** * Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a pulley ratio. @@ -5075,18 +5262,21 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, anchors, and length using the world anchors. - * @bA Body A. - * @bB Body B. - * @gaA Ground anchor A. - * @gaB Ground anchor B. - * @anchorA Anchor A. - * @anchorB Anchor B. + * @param bA Body A. + * @param bB Body B. + * @param gaA Ground anchor A. + * @param gaB Ground anchor B. + * @param anchorA Anchor A. + * @param anchorB Anchor B. **/ public Initialize(bA: b2Body, bB: b2Body, gaA: b2Math.b2Vec2, gaB: b2Math.b2Vec2, anchorA: b2Math.b2Vec2, anchorB: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * A revolute joint constrains to bodies to share a common point while they are free to rotate about the point. The relative rotation about the shared point is the joint angle. You can limit the relative rotation with a joint limit that specifies a lower and upper angle. You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is provided so that infinite forces are not generated. @@ -5095,13 +5285,13 @@ module Box2D.Dynamics.Joints { /** * Enable/disable the joint limit. - * @flag True to enable, false to disable. + * @param flag True to enable, false to disable. **/ public EnableLimit(flag: bool): void; /** * Enable/disable the joint motor. - * @flag True to enable, false to diasable. + * @param flag True to enable, false to diasable. **/ public EnableMotor(flag: bool): void; @@ -5149,13 +5339,14 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; @@ -5180,23 +5371,26 @@ module Box2D.Dynamics.Joints { /** * Set the joint limits in radians. - * @lower New lower limit. - * @upper New upper limit. + * @param lower New lower limit. + * @param upper New upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor torque, usually in N-m. - * @torque New max torque. + * @param torque New max torque. **/ public SetMaxMotorTorque(torque: number): void; /** * Set the motor speed in radians per second. - * @speed New motor speed. + * @param speed New motor speed. **/ public SetMotorSpeed(speed: number); void; } +} + +module Box2D.Dynamics.Joints { /** * Revolute joint definition. This requires defining an anchor point where the bodies are joined. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. You also need to specify the initial relative angle for joint limits. This helps when saving and loading a game. The local anchor points are measured from the body's origin rather than the center of mass because: 1. you might not know where the center of mass will be. 2. if you add/remove shapes from a body and recompute the mass, the joints will be broken. @@ -5252,15 +5446,18 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, achors, and reference angle using the world anchor. - * @bA Body A. - * @bB Body B. - * @anchor Anchor. + * @param bA Body A. + * @param bB Body B. + * @param anchor Anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the island constraint solver is approximate. @@ -5281,17 +5478,21 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; } +} + +module Box2D.Dynamics.Joints { /** * Weld joint definition. You need to specify local anchor points where they are attached and the relative body angle. The position of the anchor points is important for computing the reaction torque. @@ -5317,13 +5518,15 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. - * @bA Body A. - * @bB Body B. - * @anchor Anchor. + * @param bA Body A. + * @param bB Body B. + * @param anchor Anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Math.b2Vec2): void; } } + + diff --git a/sugar/sugar-test.ts b/sugar/sugar-test.ts new file mode 100644 index 0000000000..24371fc252 --- /dev/null +++ b/sugar/sugar-test.ts @@ -0,0 +1,181 @@ +/// + +'schfifty'.add(' five'); // - > schfifty five +'dopamine'.insert('e', 3); // - > dopeamine +'spelling eror'.insert('r', -3);// - > spelling error + +'Welcome, Mr. {name}.'.assign({ name: 'Franklin' }); // - > 'Welcome, Mr. Franklin.' +'You are {1} years old today.'.assign(14); // - > 'You are 14 years old today.' +'{n} and {r}'.assign({ n: 'Cheech' }, { r: 'Chong' }); // - > 'Cheech and Chong' + +'jumpy'.at(0); // - > 'j' +'jumpy'.at(2); //- > 'm' +'jumpy'.at(5); // - > 'j' +'jumpy'.at(5, false); // - > '' +'jumpy'.at(-1); // - > 'y' +'lucky charms'.at(2, 4, 6, 8); // - > ['u', 'k', 'y', c'] + +'caps_lock'.camelize(); // - > 'CapsLock' +'moz-border-radius'.camelize(); // - > 'MozBorderRadius' +'moz-border-radius'.camelize(false); // - > 'mozBorderRadius' + +'caps_lock'.camelize(); // - > 'CapsLock' +'moz-border-radius'.camelize(); // - > 'MozBorderRadius' +'moz-border-radius'.camelize(false); // - > 'mozBorderRadius' + +'jumpy'.chars(); // - > ['j', 'u', 'm', 'p', 'y'] +'jumpy'.chars(function (c) { + // Called 5 times: "j","u","m","p","y" +}); + +'jumpy'.codes(); // - > [106, 117, 109, 112, 121] +'jumpy'.codes(function (c) { + // Called 5 times: 106, 117, 109, 112, 121 +}); + +'too \n much \n space'.compact(); // - > 'too much space' +'enough \n '.compact(); // - > 'enough' + +'a_farewell_to_arms'.dasherize(); // - > 'a-farewell-to-arms' +'capsLock'.dasherize(); // - > 'caps-lock' + +'aHR0cDovL3R3aXR0ZXIuY29tLw=='.decodeBase64(); // - > 'http://twitter.com/' +'anVzdCBnb3QgZGVjb2RlZA=='.decodeBase64(); // - > 'just got decoded!' + +'jumpy'.each(); // - > ['j', 'u', 'm', 'p', 'y'] +'jumpy'.each(/[r-z]/); // - > ['u', 'y'] +'jumpy'.each(/[r-z]/, function (m) { + // Called twice: "u", "y" +}); + +'gonna get encoded!'.encodeBase64(); // - > 'Z29ubmEgZ2V0IGVuY29kZWQh' +'http://twitter.com/'.encodeBase64(); // - > 'aHR0cDovL3R3aXR0ZXIuY29tLw==' + +'jumpy'.endsWith('py'); // - > true +'jumpy'.endsWith(/[q-z]/); // - > true +'jumpy'.endsWith('MPY'); // - > false +'jumpy'.endsWith('MPY', false); // - > true + +'

some text

'.escapeHTML(); // - > '<p>some text</p>' +'one & two'.escapeHTML(); // - > 'one & two' + +'really?'.escapeRegExp(); // - > 'really\?' +'yes.'.escapeRegExp(); // - > 'yes\.' +'(not really)'.escapeRegExp(); // - > '\(not really\)' + +'http://foo.com/"bar"'.escapeURL(); // - > 'http://foo.com/%22bar%22' +'http://foo.com/"bar"'.escapeURL(true); // - > 'http%3A%2F%2Ffoo.com%2F%22bar%22' + +'lucky charms'.first(); // - > 'l' +'lucky charms'.first(3); // - > 'luc' + +'lucky charms'.from(); // - > 'lucky charms' +'lucky charms'.from(7); // - > 'harms' + +// visual studio is not liking these characters very much. +'??? YAMADA??!'.hankaku(); // - > '??? YAMADA??!' +'??? YAMADA??!'.hankaku('a'); // - > '??? YAMADA??!' +'??? YAMADA??!'.hankaku('alphabet'); // - > '??? YAMADA??!' +'?????! 25???!'.hankaku('katakana', 'numbers'); // - > '?????! 25???!' +'?????! 25???!'.hankaku('k', 'n'); // - > '?????! 25???!' +'?????! 25???!'.hankaku('kn'); // - > '?????! 25???!' +'?????! 25???!'.hankaku('sp'); // - > '?????! 25???!' + +'jumpy'.has('py'); // - > true +'broken'.has(/[a-n]/); // - > true +'broken'.has(/[s-z]/); // - > false + +// visual studio is not liking these characters very much. +'?????'.hasArabic(); // - > true +'?????'.hasCyrillic(); // - > true +'? ?????!'.hasHangul(); // - > true +'??????'.hasKatakana(); // - > true +"l'année".hasLatin(); // - > true + +// visual studio is not liking these characters very much. +'????'.hiragana(); // - > '????' +'?????'.hiragana(); // - > '?????' +'????'.hiragana(); // - > '????' +'????'.hiragana(false); // - > '????' + +'employee_salary'.humanize(); // - > 'Employee salary' +'author_id'.humanize(); // - > 'Author' + +''.isBlank(); // - > true +' '.isBlank(); // - > true +'noway'.isBlank(); // - > false + +// visual studio is not liking these characters very much. +'?????'.isArabic(); // - > true +'?????'.isCyrillic(); // - > true +'? ?????!'.isHangul(); // - > true +'??????'.isKatakana(); // - > false +"l'année".isLatin(); // - > true + +// visual studio is not liking these characters very much. +'????'.katakana(); // - > '????' +'?????'.katakana(); // - > '?????' + +'lucky charms'.last(); // - > 's' +'lucky charms'.last(3); // - > 'rms' + +'broken wear\nand\njumpy jump'.lines(); // - > ['broken wear', 'and', 'jumpy jump'] +'broken wear\nand\njumpy jump'.lines(function (l) { + // Called three times: "broken wear", "and", "jumpy jump" +}); + +'á'.normalize(); // - > 'a' +'Ménage à trois'.normalize(); // - > 'Menage a trois' +'Volkswagen'.normalize(); // - > 'Volkswagen' +'FULLWIDTH'.normalize(); // - > 'FULLWIDTH' + +'wasabi'.pad('-'); // - > '-wasabi-' +'wasabi'.pad('-', 2); // - > '--wasabi--' +'wasabi'.padLeft('-', 2); // - > '--wasabi' +'wasabi'.padRight('-', 2); // - > 'wasabi--' + +'Once upon a time.\n\nIn the land of oz...'.paragraphs(); // - > ['Once upon a time.', 'In the land of oz...'] +'Once upon a time.\n\nIn the land of oz...'.paragraphs(function (p) { + // Called twice: "Once upon a time.", "In teh land of oz..." +}); + +'hell, no!'.parameterize(); // - > 'hell-no' + +'post'.pluralize(); // - > 'posts' +'octopus'.pluralize(); // - > 'octopi' +'sheep'.pluralize(); // - > 'sheep' +'words'.pluralize(); // - > 'words' +'CamelOctopus'.pluralize(); // - > 'CamelOctopi' + +'schfifty five'.remove('f'); // - > 'schity ive' +'schfifty five'.remove(/[a-f]/g); // - > 'shity iv' + +'

just some text

'.removeTags(); // - > '' +'

just some text

'.removeTags('b'); // - > '

just text

' + +'jumpy'.repeat(2); // - > 'jumpyjumpy' +'a'.repeat(5); // - > 'aaaaa' +'a'.repeat(0); // - > '' + +'jumpy'.reverse(); // - > 'ypmuj' +'lucky charms'.reverse(); // - > 'smrahc ykcul' + +'a'.shift(1); // - > 'b' +'?'.shift(1); //- > '?' + +'posts'.singularize(); // -> 'post' +'octopi'.singularize(); // -> 'octopus' +'sheep'.singularize(); // -> 'sheep' +'word'.singularize(); // -> 'word' +'CamelOctopi'.singularize(); // -> 'CamelOctopus' + +'camelCase'.spacify(); // - > 'camel case' +'an-ugly-string'.spacify(); // - > 'an ugly string' +'oh-no_youDid-not'.spacify().capitalize(true); // - > 'something else' + +'hello'.startsWith('hell'); // - > true +'hello'.startsWith(/[a-h]/); // - > true +'hello'.startsWith('HELL'); // - > false +'hello'.startsWith('HELL', false); // - > true + + diff --git a/sugar/sugar.d.ts b/sugar/sugar.d.ts index a2291551dc..c84c440478 100644 --- a/sugar/sugar.d.ts +++ b/sugar/sugar.d.ts @@ -1,4042 +1,4119 @@ -// sugar-1.3.6.d.ts -// (c) 2012 Josh Baldwin -// sugar.d.ts may be freely distributed under the MIT license. -// For all details and documentation: -// https://github.com/jbaldwin/sugar.d.ts - -interface String { - - /*** - * @short Adds at [index]. Negative values are also allowed. - * @param str String to add. - * @param index Index where str is added. Default = str.length - * @returns String - * @extra %insert% is provided as an alias, and is generally more readable when using an index. - * @example - * - * 'schfifty'.add(' five') -> schfifty five - * 'dopamine'.insert('e', 3) -> dopeamine - * 'spelling eror'.insert('r', -3) -> spelling error - * - ***/ - add(str: string, index?: number): string; - insert(str: string, index?: number): string; - - /*** - * @short Assigns variables to tokens in a string. - * @method assign(, , ...) - * @returns String - * @extra If an object is passed, it's properties can be assigned using - * the object's keys. If a non-object (string, number, etc.) - * is passed it can be accessed by the argument number beginning - * with 1 (as with regex tokens). Multiple objects can be passed - * and will be merged together (original objects are unaffected). - * @example - * - * 'Welcome, Mr. {name}.'.assign({ name: 'Franklin' }) -> 'Welcome, Mr. Franklin.' - * 'You are {1} years old today.'.assign(14) -> 'You are 14 years old today.' - * '{n} and {r}'.assign({ n: 'Cheech' }, { r: 'Chong' }) -> 'Cheech and Chong' - * - ***/ - assign(str: string): string; - assign(strs: string[]): string; - assign(num: number): string; - assign(nums: number[]): string; - assign(obj: { }): string; - assign(...objs: { }[]): string; - - /*** - * @short Gets the character(s) at a given index. - * @method at(, [loop] = true) - * @param index Index of the character. - * @param loop Default = true - * @returns String or String[] - * @extra When [loop] is true, overshooting the end of the string - * (or the beginning) will begin counting from the other end. - * As an alternate syntax, passing multiple indexes will get - * the characters at those indexes. - * @example - * - * 'jumpy'.at(0) -> 'j' - * 'jumpy'.at(2) -> 'm' - * 'jumpy'.at(5) -> 'j' - * 'jumpy'.at(5, false) -> '' - * 'jumpy'.at(-1) -> 'y' - * 'lucky charms'.at(2,4,6,8) -> ['u','k','y',c'] - * - ***/ - at(index: number, loop?: bool): string; - at(indexes: number[], loop?: bool): string[]; - - /*** - * @short Converts underscores and hyphens to camel case. - * If [first] is true the first letter will also be capitalized. - * @method camelize([first] = true) - * @param first Default = true - * @returns String - * @extra If the Inflections package is included acryonyms can also - * be defined that will be used when camelizing. - * @example - * - * 'caps_lock'.camelize() -> 'CapsLock' - * 'moz-border-radius'.camelize() -> 'MozBorderRadius' - * 'moz-border-radius'.camelize(false) -> 'mozBorderRadius' - * - ***/ - camelize(first?: bool): string; - - /*** - * @short Capitalizes the first character in the string. - * @method capitalize([all] = false) - * @param all Default = false - * @returns String - * @extra If [all] is true, all words in the string will be capitalized. - * @example - * - * 'hello'.capitalize() -> 'Hello' - * 'hello kitty'.capitalize() -> 'Hello kitty' - * 'hello kitty'.capitalize(true) -> 'Hello Kitty' - * - ***/ - capitalize(all: bool): string; - - /*** - * @short Runs callback [fn] against each character in the string. - * Returns an array of characters. - * @method chars([fn]) - * @param fn Callback function. - * @returns String[] - * @example - * - * 'jumpy'.chars() -> ['j','u','m','p','y'] - * 'jumpy'.chars(function(c) { - * // Called 5 times: "j","u","m","p","y" - * }); - * - ***/ - chars(fn?: Function): string[]; - - /*** - * @short Runs callback [fn] against each character code in the string. - Returns an array of character codes. - * @method codes([fn]) - * @param fn Callback function. - * @returns number[] - * @example - * - * 'jumpy'.codes() -> [106,117,109,112,121] - * 'jumpy'.codes(function(c) { - * // Called 5 times: 106, 117, 109, 112, 121 - * }); - * - ***/ - codes(fn?: Function): number[]; - - /*** - * @short Compacts all white space in the string to - * a single space and trims the ends. - * @method compact() - * @returns String - * @example - * - * 'too \n much \n space'.compact() -> 'too much space' - * 'enough \n '.compact() -> 'enought' - * - ***/ - compact(): string; - - /*** - * @short Converts underscores and camel casing to hypens. - * @method dasherize() - * @returns String - * @example - * - * 'a_farewell_to_arms'.dasherize() -> 'a-farewell-to-arms' - * 'capsLock'.dasherize() -> 'caps-lock' - * - ***/ - dasherize(): string; - - /*** - * @short Decodes the string from base64 encoding. - * @method decodeBase64() - * @returns String - * @extra This method wraps the browser native %atob% when available, - and uses a custom implementation when not available. - * @example - * - * 'aHR0cDovL3R3aXR0ZXIuY29tLw=='.decodeBase64() -> 'http://twitter.com/' - * 'anVzdCBnb3QgZGVjb2RlZA=='.decodeBase64() -> 'just got decoded!' - * - ***/ - decodeBase64(): string; - - /*** - * @short Runs callback [fn] against each occurence of [search]. - * @method each([search] = single character, [fn]) - * @returns Array - * @extra Returns an array of matches. [search] may be either - * a string or regex, and defaults to every character in the string. - * @example - * - * 'jumpy'.each() -> ['j','u','m','p','y'] - * 'jumpy'.each(/[r-z]/) -> ['u','y'] - * 'jumpy'.each(/[r-z]/, function(m) { - * // Called twice: "u", "y" - * }); - * - ***/ - each(): string[]; - each(search: string, fn?: Function): string[]; - each(search: RegExp, fn?: Function): string[]; - each(search: Function): string[]; - - /*** - * @short Encodes the string into base64 encoding. - * @method encodeBase64() - * @returns String - * @extra This method wraps the browser native %btoa% when available, - * and uses a custom implementation when not available. - * @example - * - * 'gonna get encoded!'.encodeBase64() -> 'Z29ubmEgZ2V0IGVuY29kZWQh' - * 'http://twitter.com/'.encodeBase64() -> 'aHR0cDovL3R3aXR0ZXIuY29tLw==' - * - ***/ - encodeBase64(): string; - - /*** - * @short Returns true if the string ends with . - * @method endsWith(, [case] = true) - * @returns Boolean - * @extra may be either a string or regex. Case - * sensitive if [case] is true. - * @example - * - * 'jumpy'.endsWith('py') -> true - * 'jumpy'.endsWith(/[q-z]/) -> true - * 'jumpy'.endsWith('MPY') -> false - * 'jumpy'.endsWith('MPY', false) -> true - * - ***/ - endsWith(find: string, case_?: bool): bool; - endsWith(find: RegExp, case_?: bool): bool; - - /*** - * @short Converts HTML characters to their entity equivalents. - * @method escapeHTML() - * @returns String - * @example - * - * '

some text

'.escapeHTML() -> '<p>some text</p>' - * 'one & two'.escapeHTML() -> 'one & two' - * - ***/ - escapeHTML(): string; - - /*** - * @short Escapes all RegExp tokens in the string. - * @method escapeRegExp() - * @returns String - * @example - * - * 'really?'.escapeRegExp() -> 'really\?' - * 'yes.'.escapeRegExp() -> 'yes\.' - * '(not really)'.escapeRegExp() -> '\(not really\)' - * - ***/ - escapeRegExp(): string; - - /*** - * @short Escapes characters in a string to make a valid URL. - * @method escapeURL([param] = false) - * @returns String - * @extra If [param] is true, it will also escape valid URL - * characters for use as a URL parameter. - * @example - * - * 'http://foo.com/"bar"'.escapeURL() -> 'http://foo.com/%22bar%22' - * 'http://foo.com/"bar"'.escapeURL(true) -> 'http%3A%2F%2Ffoo.com%2F%22bar%22' - * - ***/ - escapeURL(param?: bool): string; - - /*** - * @short Returns the first [n] characters of the string. - * @method first([n] = 1) - * @returns String - * @example - * - * 'lucky charms'.first() -> 'l' - * 'lucky charms'.first(3) -> 'luc' - * - ***/ - first(n?: number): string; - - /*** - * @short Returns a section of the string starting from [index]. - * @method from([index] = 0) - * @returns String - * @example - * - * 'lucky charms'.from() -> 'lucky charms' - * 'lucky charms'.from(7) -> 'harms' - * - ***/ - from(index?: number): string; - - /*** - * @short Converts full-width characters (zenkaku) to half-width (hankaku). - * @method hankaku([mode] = 'all') - * @returns String - * @extra [mode] accepts any combination of - * "a" (alphabet), - * "n" (numbers), - * "k" (katakana), - * "s" (spaces), - * "p" (punctuation), - * or "all". - * @example - * - * 'タロウ YAMADAã§ã™ï¼'.hankaku() -> 'タロウ YAMADAã§ã™!' - * 'タロウ YAMADAã§ã™ï¼'.hankaku('a') -> 'タロウ YAMADAã§ã™ï¼' - * 'タロウ YAMADAã§ã™ï¼'.hankaku('alphabet') -> 'タロウ YAMADAã§ã™ï¼' - * 'タロウã§ã™ï¼ã€€ï¼’5歳ã§ã™ï¼'.hankaku('katakana', 'numbers') -> 'タロウã§ã™ï¼ã€€25æ­³ã§ã™ï¼' - * 'タロウã§ã™ï¼ã€€ï¼’5歳ã§ã™ï¼'.hankaku('k', 'n') -> 'タロウã§ã™ï¼ã€€25æ­³ã§ã™ï¼' - * 'タロウã§ã™ï¼ã€€ï¼’5歳ã§ã™ï¼'.hankaku('kn') -> 'タロウã§ã™ï¼ã€€25æ­³ã§ã™ï¼' - * 'タロウã§ã™ï¼ã€€ï¼’5歳ã§ã™ï¼'.hankaku('sp') -> 'タロウã§ã™! 25歳ã§ã™!' - * - ***/ - hankaku(mode?: string): string; - - /*** - * @short Returns true if the string matches . - * @method has() - * @returns Boolean - * @extra may be a string or regex. - * @example - * - * 'jumpy'.has('py') -> true - * 'broken'.has(/[a-n]/) -> true - * 'broken'.has(/[s-z]/) -> false - * - ***/ - has(find: string): bool; - has(find: RegExp): bool; - - /*** - * @short Returns true if the string contains any characters in that script. - * @method has[Script]() - * @returns Boolean - * - * @set - * hasArabic - * hasCyrillic - * hasGreek - * hasHangul - * hasHan - * hasKanji - * hasHebrew - * hasHiragana - * hasKana - * hasKatakana - * hasLatin - * hasThai - * hasDevanagari - * - * @example - * - * 'أتكلم'.hasArabic() -> true - * 'визит'.hasCyrillic() -> true - * '잘 먹겠습니다!'.hasHangul() -> true - * 'ミックスã§ã™'.hasKatakana() -> true - * "l'année".hasLatin() -> true - * - ***/ - hasArabic(): bool; - hasCyrillic(): bool; - hasGreek(): bool; - hasHangul(): bool; - hasHan(): bool; - hasKanji(): bool; - hasHebrew(): bool; - hasHiragana(): bool; - hasKana(): bool; - hasKatakana(): bool; - hasLatin(): bool; - hasThai(): bool; - hasDevanagari(): bool; - - /*** - * @method hiragana([all] = true) - * @returns String - * @short Converts katakana into hiragana. - * @extra If [all] is false, only full-width katakana will be converted. - * @example - * - * 'カタカナ'.hiragana() -> 'ã‹ãŸã‹ãª' - * 'コンニãƒãƒ'.hiragana() -> 'ã“ã‚“ã«ã¡ã¯' - * 'カタカナ'.hiragana() -> 'ã‹ãŸã‹ãª' - * 'カタカナ'.hiragana(false) -> 'カタカナ' - * - ***/ - hiragana(all?: bool): string; - - /*** - * @method humanize() - * @returns String - * @short Creates a human readable string. - * @extra Capitalizes the first word and turns underscores into spaces and strips a trailing '_id', if any. Like String#titleize, this is meant for creating pretty output. - * @example - * - * 'employee_salary'.humanize() -> 'Employee salary' - * 'author_id'.humanize() -> 'Author' - * - ***/ - humanize(): string; - - /*** - * @short Returns true if the string has a length of 0 or contains only whitespace. - * @method isBlank() - * @returns Boolean - * @example - * - * ''.isBlank() -> true - * ' '.isBlank() -> true - * 'noway'.isBlank() -> false - * - ***/ - isBlank(): bool; - - /*** - * @short Returns true if the string contains only characters in that script. Whitespace is ignored. - * @method is[Script]() - * @returns Boolean - * - * @set - * isArabic - * isCyrillic - * isGreek - * isHangul - * isHan - * isKanji - * isHebrew - * isHiragana - * isKana - * isKatakana - * isKatakana - * isThai - * isDevanagari - * - * @example - * - * 'أتكلم'.isArabic() -> true - * 'визит'.isCyrillic() -> true - * '잘 먹겠습니다!'.isHangul() -> true - * 'ミックスã§ã™'.isKatakana() -> false - * "l'année".isLatin() -> true - * - ***/ - isArabic(): bool; - isCyrillic(): bool; - isGreek(): bool; - isHangul(): bool; - isHan(): bool; - isKanji(): bool; - isHebrew(): bool; - isHiragana(): bool; - isKana(): bool; - isKatakana(): bool; - isLatin(): bool; - isThai(): bool; - isDevanagari(): bool; - - /*** - * @short Converts hiragana into katakana. - * @method katakana() - * @returns String - * @example - * - * 'ã‹ãŸã‹ãª'.katakana() -> 'カタカナ' - * 'ã“ã‚“ã«ã¡ã¯'.katakana() -> 'コンニãƒãƒ' - * - ***/ - katakana(): string; - - /*** - * @short Returns the last [n] characters of the string. - * @method last([n] = 1) - * @returns String - * @example - * - * 'lucky charms'.last() -> 's' - * 'lucky charms'.last(3) -> 'rms' - * - ***/ - last(n?: number): string; - - /*** - * @short Runs callback [fn] against each line in the string. - * Returns an array of lines. - * @method lines([fn]) - * @returns Array - * @example - * - * 'broken wear\nand\njumpy jump'.lines() -> ['broken wear','and','jumpy jump'] - * 'broken wear\nand\njumpy jump'.lines(function(l) { - * // Called three times: "broken wear", "and", "jumpy jump" - * }); - * - ***/ - lines(fn?: Function): string[]; - - /*** - * @short Finds the namespace or property indicated by the string. - * @method namespace([init] = global) - * @returns Mixed - * @extra [init] can be passed to provide a starting context, - * otherwise the global context will be used. If any - * level returns a falsy value, that will be the final result. - * @example - * - * 'Path.To.Namespace'.namespace() -> Path.To.Namespace - * '$.fn'.namespace() -> $.fn - * - ***/ - namespace(init?: any): any; - - /*** - * @short Returns the string with accented and non-standard Latin-based - * characters converted into ASCII approximate equivalents. - * @method normalize() - * @returns String - * @example - * - * 'á'.normalize() -> 'a' - * 'Ménage à trois'.normalize() -> 'Menage a trois' - * 'Volkswagen'.normalize() -> 'Volkswagen' - * 'FULLWIDTH'.normalize() -> 'FULLWIDTH' - * - ***/ - normalize(): string; - - /*** - * @short Pads either/both sides of the string. - * @method pad[Side]( = '', [num] = 1) - * @returns String - * @extra [num] is the number of characters on each side, - * and [padding] is the character to pad with. - * - * @set - * pad - * padLeft - * padRight - * - * @example - * - * 'wasabi'.pad('-') -> '-wasabi-' - * 'wasabi'.pad('-', 2) -> '--wasabi--' - * 'wasabi'.padLeft('-', 2) -> '--wasabi' - * 'wasabi'.padRight('-', 2) -> 'wasabi--' - * - ***/ - pad(padding: string, num?: number): string; - padLeft(padding: string, num?: number): string; - padRight(padding: string, num?: number): string; - - /*** - * @short Runs callback [fn] against each paragraph in the string. - * Returns an array of paragraphs. - * @method paragraphs([fn]) - * @returns Array - * @extra A paragraph here is defined as a block of text bounded - * by two or more line breaks. - * @example - * - * 'Once upon a time.\n\nIn the land of oz...'.paragraphs() -> ['Once upon a time.','In the land of oz...'] - * 'Once upon a time.\n\nIn the land of oz...'.paragraphs(function(p) { - * // Called twice: "Once upon a time.", "In teh land of oz..." - * }); - * - ***/ - paragraphs(fn?: Function): string[]; - - /*** - * @short Replaces special characters in a string so that it may - * be used as part of a pretty URL. - * @method parameterize() - * @returns String - * @example - * - * 'hell, no!'.parameterize() -> 'hell-no' - * - ***/ - parameterize(): string; - - /*** - * @short Returns the plural form of the word in the string. - * @method pluralize() - * @returns String - * @example - * - * 'post'.pluralize() -> 'posts' - * 'octopus'.pluralize() -> 'octopi' - * 'sheep'.pluralize() -> 'sheep' - * 'words'.pluralize() -> 'words' - * 'CamelOctopus'.pluralize() -> 'CamelOctopi' - * - ***/ - pluralize(): string; - - /*** - * @short Removes any part of the string that matches . - * @method remove() - * @returns String - * @extra can be a string or a regex. - * @example - * - * 'schfifty five'.remove('f') -> 'schity ive' - * 'schfifty five'.remove(/[a-f]/g) -> 'shity iv' - * - ***/ - remove(find: string): string; - remove(find: RegExp): string; - - /*** - * @short Removes all HTML tags and their contents from the string. - * @method removeTags([tag1], [tag2], ...) - * @returns String - * @extra Tags to remove may be enumerated in the parameters, - * otherwise will remove all. - * @example - * - * '

just some text

'.removeTags() -> '' - * '

just some text

'.removeTags('b') -> '

just text

' - * - ***/ - removeTags(): string; - removeTags(tag: string): string; - removeTags(...tags: string[]): string; - - /*** - * @short Returns the string repeated [num] times. - * @method repeat([num] = 0) - * @returns String - * @example - * - * 'jumpy'.repeat(2) -> 'jumpyjumpy' - * 'a'.repeat(5) -> 'aaaaa' - * 'a'.repeat(0) -> '' - * - ***/ - repeat(num?: number): string; - - /*** - * @short Reverses the string. - * @method reverse() - * @returns String - * @example - * - * 'jumpy'.reverse() -> 'ypmuj' - * 'lucky charms'.reverse() -> 'smrahc ykcul' - * - ***/ - reverse(): string; - - /*** - * @short Shifts each character in the string places in the character map. - * @method shift() - * @returns Array - * @example - * - * 'a'.shift(1) -> 'b' - * 'ク'.shift(1) -> 'グ' - * - ***/ - shift(num: number): string[]; - - /*** - * @short The reverse of String#pluralize. - * Returns the singular form of a word in a string. - * @method singularize() - * @returns String - * @example - * - * 'posts'.singularize() -> 'post' - * 'octopi'.singularize() -> 'octopus' - * 'sheep'.singularize() -> 'sheep' - * 'word'.singularize() -> 'word' - * 'CamelOctopi'.singularize() -> 'CamelOctopus' - * - ***/ - singularize(): string; - - /*** - * @short Converts camel case, underscores, and hyphens to a properly spaced string. - * @method spacify() - * @returns String - * @example - * - * 'camelCase'.spacify() -> 'camel case' - * 'an-ugly-string'.spacify() -> 'an ugly string' - * 'oh-no_youDid-not'.spacify().capitalize(true) -> 'something else' - * - ***/ - spacify(): string; - - /*** - * @short Returns true if the string starts with . - * @method startsWith(, [case] = true) - * @returns Boolean - * @extra may be either a string or regex. - * Case sensitive if [case] is true. - * @example - * - * 'hello'.startsWith('hell') -> true - * 'hello'.startsWith(/[a-h]/) -> true - * 'hello'.startsWith('HELL') -> false - * 'hello'.startsWith('HELL', false) -> true - * - ***/ - startsWith(find: string, case_?: bool): bool; - startsWith(find: RegExp, case_?: bool): bool; - - /*** - * @short Strips all HTML tags from the string. - * @method stripTags([tag1], [tag2], ...) - * @returns String - * @extra Tags to strip may be enumerated in the parameters, - * otherwise will strip all. - * @example - * - * '

just some text

'.stripTags() -> 'just some text' - * '

just some text

'.stripTags('p') -> 'just some text' - * - ***/ - stripTags(): string; - stripTags(tag: string): string; - stripTags(...tags: string[]): string; - - /*** - * @short Creates a title version of the string. - * @method titleize() - * @returns String - * @extra Capitalizes all the words and replaces some characters - * in the string to create a nicer looking title. - * String#titleize is meant for creating pretty output. - * @example - * - * 'man from the boondocks'.titleize() -> 'Man from the Boondocks' - * 'x-men: the last stand'.titleize() -> 'X Men: The Last Stand' - * 'TheManWithoutAPast'.titleize() -> 'The Man Without a Past' - * 'raiders_of_the_lost_ark'.titleize() -> 'Raiders of the Lost Ark' - * - ***/ - titleize(): string; - - /*** - * @short Returns a section of the string ending at [index]. - * @method to([index] = end) - * @returns String - * @example - * - * 'lucky charms'.to() -> 'lucky charms' - * 'lucky charms'.to(7) -> 'lucky ch' - * - ***/ - to(index?: number): string; - - /*** - * @short Converts the string into a number. - * @method toNumber([base] = 10) - * @returns Number - * @extra Any value with a "." fill be converted to a floating point value, - * otherwise an integer. - * @example - * - * '153'.toNumber() -> 153 - * '12,000'.toNumber() -> 12000 - * '10px'.toNumber() -> 10 - * 'ff'.toNumber(16) -> 255 - * - ***/ - toNumber(base?: number): number; - - /*** - * @short Removes leading and/or trailing whitespace from the string. - * @method trim[Side]() - * @returns String - * @extra Whitespace is defined as line breaks, tabs, and any character - * in the "Space, Separator" Unicode category, conforming to the - * the ES5 spec. The standard %trim% method is only added when - * not fully supported natively. - * - * @set - * trim - * trimLeft - * trimRight - * - * @example - * - * ' wasabi '.trim() -> 'wasabi' - * ' wasabi '.trimLeft() -> 'wasabi ' - * ' wasabi '.trimRight() -> ' wasabi' - * - ***/ - // Duplicate from lib.d.ts - // trim(): string; - trimLeft(): string; - trimRight(): string; - - /*** - * @short Truncates a string. - * @method truncate(, [split] = true, [from] = 'right', [ellipsis] = '...') - * @returns Object - * @extra If [split] is %false%, will not split words up, and instead - * discard the word where the truncation occurred. [from] can - * also be %"middle"% or %"left"%. - * @example - * - * 'just sittin on the dock of the bay'.truncate(20) -> 'just sittin on the do...' - * 'just sittin on the dock of the bay'.truncate(20, false) -> 'just sittin on the...' - * 'just sittin on the dock of the bay'.truncate(20, true, 'middle') -> 'just sitt...of the bay' - * 'just sittin on the dock of the bay'.truncate(20, true, 'left') -> '...the dock of the bay' - * - ***/ - truncate(length: number, split?: bool, from?: string, ellipsis?: string): string; - - /*** - * @short Converts hyphens and camel casing to underscores. - * @method underscore() - * @returns String - * @example - * - * 'a-farewell-to-arms'.underscore() -> 'a_farewell_to_arms' - * 'capsLock'.underscore() -> 'caps_lock' - * - ***/ - underscore(): string; - - /*** - * @short Restores escaped HTML characters. - * @method unescapeHTML([partial] = false) - * @returns String - * @example - * - * '<p>some text</p>'.unescapeHTML() -> '

some text

' - * 'one & two'.unescapeHTML() -> 'one & two' - * - ***/ - unescapeHTML(partial?: bool): string; - - /*** - * @short Restores escaped characters in a URL escaped string. - * @method unescapeURL([partial] = false) - * @returns String - * @extra If [partial] is true, it will only unescape non-valid URL characters. [partial] is included here for completeness, but should very rarely be needed. - * @example - * - * 'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL() -> 'http://foo.com/the bar' - * 'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL(true) -> 'http%3A%2F%2Ffoo.com%2Fthe bar' - * - ***/ - unescapeURL(partial?: bool): string; - - /*** - * @short Runs callback [fn] against each word in the string. - * Returns an array of words. - * @method words([fn]) - * @returns String[] - * @extra A "word" here is defined as any sequence of non-whitespace characters. - * @example - * - * 'broken wear'.words() -> ['broken','wear'] - * 'broken wear'.words(function(w) { - * // Called twice: "broken", "wear" - * }); - * - ***/ - words(fn?: Function): string[]; - - /*** - * @short Converts half-width characters (hankaku) to full-width (zenkaku). - * @method zenkaku([mode] = 'all') - * @returns String - * @extra [mode] accepts any combination of - * "a" (alphabet), - * "n" (numbers), - * "k" (katakana), - * "s" (spaces), - * "p" (punctuation), - * or "all". - * @example - * - * 'タロウ YAMADAã§ã™!'.zenkaku() -> 'タロウ YAMADAã§ã™ï¼' - * 'タロウ YAMADAã§ã™!'.zenkaku('a') -> 'タロウ YAMADAã§ã™!' - * 'タロウ YAMADAã§ã™!'.zenkaku('alphabet') -> 'タロウ YAMADAã§ã™!' - * 'タロウã§ã™! 25æ­³ã§ã™!'.zenkaku('katakana', 'numbers') -> 'タロウã§ã™! 25歳ã§ã™!' - * 'タロウã§ã™! 25æ­³ã§ã™!'.zenkaku('k', 'n') -> 'タロウã§ã™! 25歳ã§ã™!' - * 'タロウã§ã™! 25æ­³ã§ã™!'.zenkaku('kn') -> 'タロウã§ã™! 25歳ã§ã™!' - * 'タロウã§ã™! 25æ­³ã§ã™!'.zenkaku('sp') -> 'タロウã§ã™ï¼ã€€25æ­³ã§ã™ï¼' - * - ***/ - zenkaku(mode?: string): string; -} - -interface Number { - - /*** - * @short Returns a random integer between [n1] and [n2]. - * @method Number.random([n1], [n2]) - * @returns Number - * @extra If only 1 number is passed, the other will be 0. If none are passed, the number will be either 0 or 1. - * @example - * - * Number.random(50, 100) -> ex. 85 - * Number.random(50) -> ex. 27 - * Number.random() -> ex. 0 - * - ***/ - random(n1?: number, n2?: number): number; - - /*** - * @short Returns an abbreviated form of the number. - * @method abbr([precision] = 0) - * @returns String - * @extra [precision] will round to the given precision. - * @example - * - * (1000).abbr() -> "1k" - * (1000000).abbr() -> "1m" - * (1280).abbr(1) -> "1.3k" - * - ***/ - abbr(precision?: number): string; - - /*** - * @short Returns an abbreviated form of the number, considered to be "Bytes". - * @method bytes([precision] = 0, [limit] = 4) - * @returns String - * @extra [precision] will round to the given precision. - * [limit] is the upper limit for the units. - * The default is %4%, which is "terabytes" (TB). - * If [limit] is %false%, the upper limit will be "exa". - * @example - * - * (1000).bytes() -> "1kB" - * (1000).bytes(2) -> "0.98kB" - * ((10).pow(20)).bytes() -> "90,949,470TB" - * ((10).pow(20)).bytes(0, false) -> "87EB" - * - ***/ - bytes(precision?: number, limit?: number): string; - bytes(precision?: number, limit?: bool): string; - - /*** - * @short Shortcut for %Math.ceil% that also allows a . - * @method ceil( = 0) - * @returns Number - * - * @example - * - * (3.241).ceil() -> 4 - * (-3.241).ceil() -> -3 - * (3.241).ceil(2) -> 3.25 - * (3748).ceil(-2) -> 3800 - * - ***/ - ceil(precision?: number): number; - - /*** - * @short Returns a string at the code point of the number. - * @method chr() - * @returns String - * @example - * - * (65).chr() -> "A" - * (75).chr() -> "K" - * - ***/ - chr(): string; - - /*** - * @short Returns an array containing numbers from the number down to . - * @method downto(, [fn], [step] = 1) - * @returns Array - * @extra Optionally calls [fn] callback for each number in that array. - * [step] allows multiples greater than 1. - * @example - * - * (8).downto(3) -> [8, 7, 6, 5, 4, 3] - * (8).downto(3, function(n) { - * // This function is called 6 times receiving n as the value. - * }); - * (8).downto(2, null, 2) -> [8, 6, 4, 2] - * - ***/ - downto(num: number, fn?: Function, step?: number): number[]; - - /*** - * @short Takes the number as milliseconds and returns a unit- - * adjusted localized string. - * @method duration([locale] = currentLocale) - * @returns String - * @extra This method is the same as %Date#relative% without - * the localized equivalent of "from now" or "ago". - * [locale] can be passed as the first (and only) parameter. - * Note that this method is only available when the dates - * package is included. - * @example - * - * (500).duration() -> '500 milliseconds' - * (1200).duration() -> '1 second' - * (75).minutes().duration() -> '1 hour' - * (75).minutes().duration('es') -> '1 hora' - * - ***/ - duration(locale?: string): string; - - /*** - * @short Shortcut for %Math.floor% that also allows a . - * @method floor( = 0) - * @returns Number - * @example - * - * (3.241).floor() -> 3 - * (-3.841).floor() -> -4 - * (3.241).floor(2) -> 3.24 - * (3748).floor(-2) -> 3700 - * - ***/ - floor(precision?: number): number; - - /*** - * @short Formats the number to a readable string. - * @method format([place] = 0, [thousands] = ',', [decimal] = '.') - * @returns String - * @extra If [place] is %undefined%, will automatically determine the place. - * [thousands] is the character used for the thousands separator. - * [decimal] is the character used for the decimal point. - * @example - * - * (56782).format() -> '56,782' - * (56782).format(2) -> '56,782.00' - * (4388.43).format(2, ' ') -> '4 388.43' - * (4388.43).format(2, '.', ',') -> '4.388,43' - * - ***/ - format(place?: number, thousands?: string, decimal?: string): string; - - /*** - * @short Converts the number to hexidecimal. - * @method hex([pad] = 1) - * @returns String - * @extra [pad] will pad the resulting string to that many places. - * @example - * - * (255).hex() -> 'ff'; - * (255).hex(4) -> '00ff'; - * (23654).hex() -> '5c66'; - * - ***/ - hex(pad?: number): string; - - /*** - * @short Returns true if the number is even. - * @method isEven() - * @returns Boolean - * @example - * - * (6).isEven() -> true - * (17).isEven() -> false - * - ***/ - isEven(): bool; - - /*** - * @short Returns true if the number has no trailing decimal. - * @method isInteger() - * @returns Boolean - * @example - * - * (420).isInteger() -> true - * (4.5).isInteger() -> false - * - ***/ - isInteger(): bool; - - /*** - * @short Returns true if the number is a multiple of . - * @method isMultipleOf() - * @returns Boolean - * @example - * - * (6).isMultipleOf(2) -> true - * (17).isMultipleOf(2) -> false - * (32).isMultipleOf(4) -> true - * (34).isMultipleOf(4) -> false - * - ***/ - isMultipleOf(num: number): bool; - - /*** - * @short Returns true if the number is odd. - * @method isOdd() - * @returns Boolean - * @example - * - * (3).isOdd() -> true - * (18).isOdd() -> false - * - ***/ - isOdd(): bool; - - /*** - * @short Returns the logarithm of the number with base , - * or natural logarithm of the number if is undefined. - * @method log( = Math.E) - * @returns Number - * @example - * - * (64).log(2) -> 6 - * (9).log(3) -> 2 - * (5).log() -> 1.6094379124341003 - * - ***/ - log(base?: number): number; - - /*** - * @short Math related functions are mapped as shortcuts to numbers and are identical. Note that %Number#log% provides some special defaults. - * @method [math]() - * @returns Number - * - * @set - * abs - * sin - * asin - * cos - * acos - * tan - * atan - * sqrt - * exp - * pow - * - * @example - * - * (3).pow(3) -> 27 - * (-3).abs() -> 3 - * (1024).sqrt() -> 32 - * - ***/ - abs(): number; - sin(): number; - asin(): number; - cos(): number; - acos(): number; - tan(): number; - atan(): number; - sqrt(): number; - exp(): number; - pow(num: number): number; - - /*** - * @short Returns the number as a string in metric notation. - * @method metric([precision] = 0, [limit] = 1) - * @returns String - * @extra [precision] will round to the given precision. - * Both very large numbers and very small numbers are supported. - * [limit] is the upper limit for the units. - * The default is %1%, which is "kilo". - * If [limit] is %false%, the upper limit will be "exa". - * The lower limit is "nano", and cannot be changed. - * @example - * - * (1000).metric() -> "1k" - * (1000000).metric() -> "1,000k" - * (1000000).metric(0, false) -> "1M" - * (1249).metric(2) + 'g' -> "1.25kg" - * (0.025).metric() + 'm' -> "25mm" - * - ***/ - metric(precision?: number, limit?: number): string; - metric(precision?: number, limit?: bool): string; - - /*** - * @short Returns an ordinalized (English) string, i.e. "1st", "2nd", etc. - * @method ordinalize() - * @returns String - * @example - * - * (1).ordinalize() -> '1st'; - * (2).ordinalize() -> '2nd'; - * (8).ordinalize() -> '8th'; - * - ***/ - ordinalize(): string; - - /*** - * @short Pads a number with "0" to . - * @method pad( = 0, [sign] = false, [base] = 10) - * @returns String - * @extra [sign] allows you to force the sign as well (+05, etc). [base] can change the base for numeral conversion. - * @example - * - * (5).pad(2) -> '05' - * (-5).pad(4) -> '-0005' - * (82).pad(3, true) -> '+082' - * - ***/ - pad(place?: number, sign?: bool, base?: number): string; - - /*** - * @short Shortcut for %Math.round% that also allows a . - * @method round( = 0) - * @returns Number - * - * @example - * - * (3.241).round() -> 3 - * (-3.841).round() -> -4 - * (3.241).round(2) -> 3.24 - * (3748).round(-2) -> 3800 - * - ***/ - round(precision?: number): number; - - /*** - * @short Calls a number of times equivalent to the number. - * @method times() - * @returns Number - * @example - * - * (8).times(function(i) { - * // This function is called 8 times. - * }); - * - ***/ - times(fn: Function): number; - - /*** - * @short Returns a number. This is mostly for compatibility reasons. - * @method toNumber() - * @returns Number - * @example - * - * (420).toNumber() -> 420 - * - ***/ - toNumber(): number; - - /*** - * @short Takes the number as a corresponding unit of time and - * converts to milliseconds. - * @method [unit]() - * @returns Number - * @extra Method names can be both singular and plural. - * Note that as "a month" is ambiguous as a unit of time, - * %months% will be equivalent to 30.4375 days, the average - * number in a month. Be careful using %months% if you need - * exact precision. - * - * @set - * millisecond - * milliseconds - * second - * seconds - * minute - * minutes - * hour - * hours - * day - * days - * week - * weeks - * month - * months - * year - * years - * - * @example - * - * (5).milliseconds() -> 5 - * (10).hours() -> 36000000 - * (1).day() -> 86400000 - * - ***/ - millisecond(): number; - milliseconds(): number; - second(): number; - seconds(): number; - minute(): number; - minutes(): number; - hour(): number; - hours(): number; - day(): number; - days(): number; - week(): number; - weeks(): number; - month(): number; - months(): number; - year(): number; - years(): number; - - /*** - * @short Returns a date units after [d], where is the number. - * @method [unit]After([d], [locale] = currentLocale) - * @returns Date - * @extra [d] will accept a date object, timestamp, or text format. - * Note that "months" is ambiguous as a unit of time. If the - * target date falls on a day that does not exist - * (ie. August 31 -> February 31), the date will be shifted - * to the last day of the month. Be careful using %monthsAfter% - * if you need exact precision. See @date_format for more. - * - * @set - * millisecondAfter - * millisecondsAfter - * secondAfter - * secondsAfter - * minuteAfter - * minutesAfter - * hourAfter - * hoursAfter - * dayAfter - * daysAfter - * weekAfter - * weeksAfter - * monthAfter - * monthsAfter - * yearAfter - * yearsAfter - * - * @example - * - * (5).daysAfter('tuesday') -> 5 days after tuesday of this week - * (1).yearAfter('January 23, 1997') -> January 23, 1998 - * - ***/ - millisecondAfter(d: string, locale?: string): Date; - millisecondAfter(d: Date, locale?: string): Date; - millisecondsAfter(d: string, locale?: string): Date; - millisecondsAfter(d: Date, locale?: string): Date; - secondAfter(d: string, locale?: string): Date; - secondAfter(d: Date, locale?: string): Date; - secondsAfter(d: string, locale?: string): Date; - secondsAfter(d: Date, locale?: string): Date; - minuteAfter(d: string, locale?: string): Date; - minuteAfter(d: Date, locale?: string): Date; - minutesAfter(d: string, locale?: string): Date; - minutesAfter(d: Date, locale?: string): Date; - hourAfter(d: string, locale?: string): Date; - hourAfter(d: Date, locale?: string): Date; - hoursAfter(d: string, locale?: string): Date; - hoursAfter(d: Date, locale?: string): Date; - dayAfter(d: string, locale?: string): Date; - dayAfter(d: Date, locale?: string): Date; - daysAfter(d: string, locale?: string): Date; - daysAfter(d: Date, locale?: string): Date; - weekAfter(d: string, locale?: string): Date; - weekAfter(d: Date, locale?: string): Date; - weeksAfter(d: string, locale?: string): Date; - weeksAfter(d: Date, locale?: string): Date; - monthAfter(d: string, locale?: string): Date; - monthAfter(d: Date, locale?: string): Date; - monthsAfter(d: string, locale?: string): Date; - yearAfter(d: string, locale?: string): Date; - yearAfter(d: Date, locale?: string): Date; - yearsAfter(d: string, locale?: string): Date; - yearsAfter(d: Date, locale?: string): Date; - - /*** - * @short Returns a date that is units ago. - * @method [unit]Ago() - * @returns Date - * @extra Note that "months" is ambiguous as a unit of time. - * If the target date falls on a day that does not exist - * (ie. August 31 -> February 31), the date will be shifted - * to the last day of the month. Be careful using %monthsAgo% - * if you need exact precision. - * - * @set - * millisecondAgo - * millisecondsAgo - * secondAgo - * secondsAgo - * minuteAgo - * minutesAgo - * hourAgo - * hoursAgo - * dayAgo - * daysAgo - * weekAgo - * weeksAgo - * monthAgo - * monthsAgo - * yearAgo - * yearsAgo - * - * @example - * - * (5).weeksAgo() -> 5 weeks ago - * (1).yearAgo() -> January 23, 1996 - * - ***/ - millisecondAgo(): Date; - millisecondsAgo(): Date; - secondAgo(): Date; - secondsAgo(): Date; - minuteAgo(): Date; - minutesAgo(): Date; - hourAgo(): Date; - hoursAgo(): Date; - dayAgo(): Date; - daysAgo(): Date; - weekAgo(): Date; - weeksAgo(): Date; - monthAgo(): Date; - monthsAgo(): Date; - yearAgo(): Date; - yearsAgo(): Date; - - /*** - * @short Returns a date that is units before [d], where is the number. - * @method [unit]Before([d], [locale] = currentLocale) - * @returns Date - * @extra [d] will accept a date object, timestamp, or text format. - * Note that "months" is ambiguous as a unit of time. If the - * target date falls on a day that does not exist - * (ie. August 31 -> February 31), the date will be shifted to - * the last day of the month. Be careful using %monthsBefore% - * if you need exact precision. See @date_format for more. - * - * @set - * millisecondBefore - * millisecondsBefore - * secondBefore - * secondsBefore - * minuteBefore - * minutesBefore - * hourBefore - * hoursBefore - * dayBefore - * daysBefore - * weekBefore - * weeksBefore - * monthBefore - * monthsBefore - * yearBefore - * yearsBefore - * - * @example - * - * (5).daysBefore('tuesday') -> 5 days before tuesday of this week - * (1).yearBefore('January 23, 1997') -> January 23, 1996 - * - ***/ - millisecondBefore(d: string, locale?: string): Date; - millisecondBefore(d: Date, locale?: string): Date; - millisecondsBefore(d: string, locale?: string): Date; - millisecondsBefore(d: Date, locale?: string): Date; - secondBefore(d: string, locale?: string): Date; - secondBefore(d: Date, locale?: string): Date; - secondsBefore(d: string, locale?: string): Date; - secondsBefore(d: Date, locale?: string): Date; - minuteBefore(d: string, locale?: string): Date; - minuteBefore(d: Date, locale?: string): Date; - minutesBefore(d: string, locale?: string): Date; - minutesBefore(d: Date, locale?: string): Date; - hourBefore(d: string, locale?: string): Date; - hourBefore(d: Date, locale?: string): Date; - hoursBefore(d: string, locale?: string): Date; - hoursBefore(d: Date, locale?: string): Date; - dayBefore(d: string, locale?: string): Date; - dayBefore(d: Date, locale?: string): Date; - daysBefore(d: string, locale?: string): Date; - daysBefore(d: Date, locale?: string): Date; - weekBefore(d: string, locale?: string): Date; - weekBefore(d: Date, locale?: string): Date; - weeksBefore(d: string, locale?: string): Date; - weeksBefore(d: Date, locale?: string): Date; - monthBefore(d: string, locale?: string): Date; - monthBefore(d: Date, locale?: string): Date; - monthsBefore(d: string, locale?: string): Date; - monthsBefore(d: Date, locale?: string): Date; - yearBefore(d: string, locale?: string): Date; - yearBefore(d: Date, locale?: string): Date; - yearsBefore(d: string, locale?: string): Date; - yearsBefore(d: Date, locale?: string): Date; - - /*** - * @short Returns a date units from now. - * @method [unit]FromNow() - * @returns Date - * @extra Note that "months" is ambiguous as a unit of time. - * If the target date falls on a day that does not exist - * (ie. August 31 -> February 31), the date will be shifted - * to the last day of the month. Be careful using %monthsFromNow% - * if you need exact precision. - * - * @set - * millisecondFromNow - * millisecondsFromNow - * secondFromNow - * secondsFromNow - * minuteFromNow - * minutesFromNow - * hourFromNow - * hoursFromNow - * dayFromNow - * daysFromNow - * weekFromNow - * weeksFromNow - * monthFromNow - * monthsFromNow - * yearFromNow - * yearsFromNow - * - * @example - * - * (5).weeksFromNow() -> 5 weeks ago - * (1).yearFromNow() -> January 23, 1998 - * - ***/ - millisecondFromNow(): Date; - millisecondsFromNow(): Date; - secondFromNow(): Date; - secondsFromNow(): Date; - minuteFromNow(): Date; - minutesFromNow(): Date; - hourFromNow(): Date; - hoursFromNow(): Date; - dayFromNow(): Date; - daysFromNow(): Date; - weekFromNow(): Date; - weeksFromNow(): Date; - monthFromNow(): Date; - monthsFromNow(): Date; - yearFromNow(): Date; - yearsFromNow(): Date; - - /*** - * @short Returns an array containing numbers from the number up to . - * @method upto(, [fn], [step] = 1) - * @returns Array - * @extra Optionally calls [fn] callback for each number in that array. - * [step] allows multiples greater than 1. - * @example - * - * (2).upto(6) -> [2, 3, 4, 5, 6] - * (2).upto(6, function(n) { - * // This function is called 5 times receiving n as the value. - * }); - * (2).upto(8, null, 2) -> [2, 4, 6, 8] - * - ***/ - upto(num: number, fn?: Function, step?: number): number[]; -} - -interface Array { - - /*** - * @short Alternate array constructor. - * @method Array.create(, , ...) - * @returns Array - * @extra This method will create a single array by calling %concat% - * on all arguments passed. In addition to ensuring that an unknown - * variable is in a single, flat array (the standard constructor will - * create nested arrays, this one will not), it is also a useful - * shorthand to convert a function's arguments object into a standard - * array. - * @example - * - * Array.create('one', true, 3) -> ['one', true, 3] - * Array.create(['one', true, 3]) -> ['one', true, 3] - + Array.create(function(n) { - * return arguments; - * }('howdy', 'doody')); - * - ***/ - create(...args: any[]): any[]; - - /*** - * @short Returns true if is an Array. - * @method Array.isArray() - * @returns Boolean - * @extra This method is provided for browsers that don't support it internally. - * @example - * - * Array.isArray(3) -> false - * Array.isArray(true) -> false - * Array.isArray('wasabi') -> false - * Array.isArray([1,2,3]) -> true - * - ***/ - isArray(obj: any): bool; - - /*** - * @short Adds to the array. - * @method add(, [index]) - * @returns Array - * @extra If [index] is specified, it will add at [index], otherwise - * adds to the end of the array. %add% behaves like %concat% - * in that if is an array it will be joined, not inserted. - * This method will change the array! Use %include% for a - * non-destructive alias. Also, %insert% is provided as an - * alias that reads better when using an index. - * @example - * - * [1,2,3,4].add(5) -> [1,2,3,4,5] - * [1,2,3,4].add([5,6,7]) -> [1,2,3,4,5,6,7] - * [1,2,3,4].insert(8, 1) -> [1,8,2,3,4] - * - ***/ - add(el: any, index?: number): any[]; - add(el: any[], index?: number): any[]; - insert(el: any, index?: number): any[]; - insert(el: any[], index?: number): any[]; - - /*** - * @short Gets the element(s) at a given index. - * @method at(, [loop] = true) - * @returns Mixed - * @extra When [loop] is true, overshooting the end of the array (or the beginning) will begin counting from the other end. As an alternate syntax, passing multiple indexes will get the elements at those indexes. - * @example - * - * [1,2,3].at(0) -> 1 - * [1,2,3].at(2) -> 3 - * [1,2,3].at(4) -> 2 - * [1,2,3].at(4, false) -> null - * [1,2,3].at(-1) -> 3 - * [1,2,3].at(0,1) -> [1,2] - * - ***/ - at(index: number, loop?: bool): any; - at(start: number, stop: number): any[]; - - /*** - * @short Averages all values in the array. - * @method average([map]) - * @returns Number - * @extra [map] may be a function mapping the value to be averaged or - * a string acting as a shortcut. - * @example - * - * [1,2,3].average() -> 2 - + [{age:35},{age:11},{age:11}].average(function(n) { - * return n.age; - * }); -> 19 - * [{age:35},{age:11},{age:11}].average('age') -> 19 - * - ***/ - average(map?: (n: number) => number): number; - - /*** - * @short Clones the array. - * @method clone() - * @returns Array - * @example - * - * [1,2,3].clone() -> [1,2,3] - * - ***/ - clone(): any[]; - - /*** - * @short Removes all instances of %undefined%, %null%, and %NaN% from the array. - * @method compact([all] = false) - * @returns Array - * @extra If [all] is %true%, all "falsy" elements will be removed. This includes empty strings, 0, and false. - * @example - * - * [1,null,2,undefined,3].compact() -> [1,2,3] - * [1,'',2,false,3].compact() -> [1,'',2,false,3] - * [1,'',2,false,3].compact(true) -> [1,2,3] - * - ***/ - compact(all?: bool): any[]; - - /*** - * @short Counts all elements in the array that match . - * @method count() - * @returns Number - * @extra will match a string, number, array, object, or alternately test against a function or regex. This method implements @array_matching. - * @example - * - * [1,2,3,1].count(1) -> 2 - * ['a','b','c'].count(/b/) -> 1 - + [{a:1},{b:2}].count(function(n) { - * return n['a'] > 1; - * }); -> 0 - * - ***/ - count(f: number): number; - count(f: string): number; - count(f: any[]): number; - count(f: Object): number; - count(f: (n: any) => any): number; - count(f: RegExp): number; - - /*** - * @short Runs against each element in the array. Enhanced version of %Array#forEach%. - * @method each(, [index] = 0, [loop] = false) - * @returns Array - * @extra Parameters passed to are identical to %forEach%, - * ie. the first parameter is the current element, second - * parameter is the current index, and third parameter is - * the array itself. If returns %false% at any time - * it will break out of the loop. Once %each% finishes, - * it will return the array. If [index] is passed, will - * begin at that index and work its way to the end. If [loop] - * is true, it will then start over from the beginning of the - * array and continue until it reaches [index] - 1. - * @example - * - * [1,2,3,4].each(function(n) { - * // Called 4 times: 1, 2, 3, 4 - * }); - * [1,2,3,4].each(function(n) { - * // Called 4 times: 3, 4, 1, 2 - * }, 2, true); - * - ***/ - each(fn: (el: any, i?: number, array?: any[]) => bool, - index?: number, - loop?: bool): any[]; - - /*** - * @short Returns true if all elements in the array match . - * @method every(, [scope]) - * @returns Boolean - * @extra [scope] is the %this% object. %all% is provided an alias. - * In addition to providing this method for browsers that don't - * support it natively, this method also implements @array_matching. - * @example - * - + ['a','a','a'].every(function(n) { - * return n == 'a'; - * }); - * ['a','a','a'].every('a') -> true - * [{a:2},{a:2}].every({a:2}) -> true - ***/ - every(f: number, scope?: any): bool; - every(f: string, scope?: any): bool; - every(f: Object, scope?: any): bool; - every(f: (el: any, i?: number, array?: any[]) => bool, scope?: any): bool; - all(f: number, scope?: any): bool; - all(f: string, scope?: any): bool; - all(f: Object, scope?: any): bool; - all(f: (el: any, i?: number, array?: any[]) => bool, scope?: any): bool; - - /*** - * @short Removes any element in the array that matches [f1], [f2], etc. - * @method exclude([f1], [f2], ...) - * @returns Array - * @extra This is a non-destructive alias for %remove%. It will not change the original array. This method implements @array_matching. - * @example - * - * [1,2,3].exclude(3) -> [1,2] - * ['a','b','c'].exclude(/b/) -> ['a','c'] - * [{a:1},{b:2}].exclude(function(n) { - * return n['a'] == 1; - * }); -> [{b:2}] - * - ***/ - exclude(...f: number[]): number[]; - exclude(...f: string[]): string[]; - exclude(...f: RegExp[]): string[]; - exclude(...f: Object[]): Object[]; - // TODO fixme - //exclude(...f: (el: any, i?: number, array?: any[]) => bool): any[]; - - /*** - * @short Returns any elements in the array that match . - * @method filter(, [scope]) - * @returns Array - * @extra [scope] is the %this% object. In addition to providing this - * method for browsers that don't support it natively, this method - * also implements @array_matching. - * @example - * - * [1,2,3].filter(function(n) { - * return n > 1; - * }); - * [1,2,2,4].filter(2) -> 2 - * - ***/ - filter(f: number, scope?: any): number[]; - filter(f: string, scope?: any): string[]; - filter(f: RegExp, scope?: any): String[]; - filter(f: Object, scope?: any): Object[]; - filter(f: (el: any, i?: number, array?: any[]) => bool, scope?: any): any[]; - - /*** - * @short Returns the first element that matches . - * @method find(, [index] = 0, [loop] = false) - * @returns Mixed - * @extra will match a string, number, array, object, or alternately - * test against a function or regex. Starts at [index], and will - * continue once from index = 0 if [loop] is true. This method - * implements @array_matching. - * @example - * - * [{a:1,b:2},{a:1,b:3},{a:1,b:4}].find(function(n) { - * return n['a'] == 1; - * }); -> {a:1,b:3} - * ['cuba','japan','canada'].find(/^c/, 2) -> 'canada' - * - ***/ - find(f: number, index?: number, loop?: bool): number; - find(f: string, index?: number, loop?: bool): string; - find(f: RegExp, index?: number, loop?: bool): string; - find(f: Object, index?: number, loop?: bool): Object; - find(f: (el: any, i?: number, array?: any[]) => bool, index?: number, loop?: bool): any; - - /*** - * @short Returns all elements that match . - * @method findAll(, [index] = 0, [loop] = false) - * @returns Array - * @extra will match a string, number, array, object, or alternately - * test against a function or regex. Starts at [index], and will - * continue once from index = 0 if [loop] is true. This method - * implements @array_matching. - * @example - * - * [{a:1,b:2},{a:1,b:3},{a:2,b:4}].findAll(function(n) { - * return n['a'] == 1; - * }); -> [{a:1,b:3},{a:1,b:4}] - * ['cuba','japan','canada'].findAll(/^c/) -> 'cuba','canada' - * ['cuba','japan','canada'].findAll(/^c/, 2) -> 'canada' - * - ***/ - findAll(f: number, index?: number, loop?: bool): number[]; - findAll(f: string, index?: number, loop?: bool): string[]; - findAll(f: RegExp, index?: number, loop?: bool): string[]; - findAll(f: Object, index?: number, loop?: bool): Object[]; - findAll(f: (el: any, i?: number, array?: any[]) => bool, index?: number, loop?: bool): any[]; - - /*** - * @short Returns the index of the first element that matches - * or -1 if not found. - * @method findIndex(, [startIndex] = 0, [loop] = false) - * @returns Number - * @extra This method has a few notable differences to native %indexOf%. - * Although will similarly match a primitive such as a string - * or number, it will also match deep objects and arrays that are - * not equal by reference (%===%). Additionally, if a function is - * passed it will be run as a matching function (similar to the - * behavior of %Array#filter%) rather than attempting to find that - * function itself by reference in the array. Starts at [index], - * and will continue once from index = 0 if [loop] is true. - * This method implements @array_matching. - * @example - * - * [1,2,3,4].findIndex(3); -> 2 - * [1,2,3,4].findIndex(function(n) { - * return n % 2 == 0; - * }); -> 1 - * ['one','two','three'].findIndex(/th/); -> 2 - * - ***/ - findIndex(f: number, startIndex?: number, loop?: bool): number; - findIndex(f: string, startIndex?: number, loop?: bool): number; - // TODO duplicate - //findIndex(f: RegExp, startIndex?: number, loop?: bool): number; - findIndex(f: Object, startIndex?: number, loop?: bool): number; - findIndex(f: RegExp, startIndex?: number, loop?: bool): number; - findIndex(f: (el: any, i?: number, array?: any[]) => bool, startIndex?: number, loop?: bool): number; - - /*** - * @short Returns the first element(s) in the array. - * @method first([num] = 1) - * @returns Mixed - * @extra When is passed, returns the first elements in the array. - * @example - * - * [1,2,3].first() -> 1 - * [1,2,3].first(2) -> [1,2] - * - ***/ - first(num?: number): any[]; - - /*** - * @short Returns a flattened, one-dimensional copy of the array. - * @method flatten([limit] = Infinity) - * @returns Array - * @extra You can optionally specify a [limit], which will only flatten - * that depth. - * @example - * - * [[1], 2, [3]].flatten() -> [1,2,3] - * [['a'],[],'b','c'].flatten() -> ['a','b','c'] - * - ***/ - flatten(limit?: number): any[]; - - /*** - * @short Iterates over the array, calling [fn] on each loop. - * @method forEach([fn], [scope]) - * @returns Nothing - * @extra This method is only provided for those browsers that do not support - * it natively. [scope] becomes the %this% object. - * @example - * - * ['a','b','c'].forEach(function(a) { - * // Called 3 times: 'a','b','c' - * }); - * - ***/ - forEach(fn: (el: any, i?: number, array?: any[]) => any, scope?: any): void; - - /*** - * @short Returns a slice of the array from . - * @method from() - * @returns Array - * @example - * - * [1,2,3].from(1) -> [2,3] - * [1,2,3].from(2) -> [3] - * - ***/ - from(index: number): any[]; - - /*** - * @short Groups the array by . - * @method groupBy(, [fn]) - * @returns Object - * @extra Will return an object with keys equal to the grouped values. - * may be a mapping function, or a string acting as a shortcut. - * Optionally calls [fn] for each group. - * @example - * - * ['fee','fi','fum'].groupBy('length') -> { 2: ['fi'], 3: ['fee','fum'] } - + [{age:35,name:'ken'},{age:15,name:'bob'}].groupBy(function(n) { - * return n.age; - * }); -> { 35: [{age:35,name:'ken'}], 15: [{age:15,name:'bob'}] } - * - ***/ - groupBy(map: string, fn?: (n: any) => void): Object; - groupBy(fn: (n: any) => void): Object; - - /*** - * @short Groups the array into arrays. - * @method inGroups(, [padding]) - * @returns Array - * @extra [padding] specifies a value with which to pad the last array - * so that they are all equal length. - * @example - * - * [1,2,3,4,5,6,7].inGroups(3) -> [ [1,2,3], [4,5,6], [7] ] - * [1,2,3,4,5,6,7].inGroups(3, 'none') -> [ [1,2,3], [4,5,6], [7,'none','none'] ] - * - ***/ - inGroups(num: number, padding?: any): any[][]; - - /*** - * @short Groups the array into arrays of elements each. - * @method inGroupsOf(, [padding] = null) - * @returns Array - * @extra [padding] specifies a value with which to pad the last array so that they are all equal length. - * @example - * - * [1,2,3,4,5,6,7].inGroupsOf(4) -> [ [1,2,3,4], [5,6,7] ] - * [1,2,3,4,5,6,7].inGroupsOf(4, 'none') -> [ [1,2,3,4], [5,6,7,'none'] ] - * - ***/ - inGroupsOf(num: number, padding?: any): any[][]; - - /*** - * @short Adds to the array. - * @method include(, [index]) - * @returns Array - * @extra This is a non-destructive alias for %add%. It will not change - * the original array. - * @example - * - * [1,2,3,4].include(5) -> [1,2,3,4,5] - * [1,2,3,4].include(8, 1) -> [1,8,2,3,4] - * [1,2,3,4].include([5,6,7]) -> [1,2,3,4,5,6,7] - * - ***/ - include(el: any, index?: number): any[]; - - /*** - * @short Searches the array and returns the first index where occurs, or -1 if the element is not found. - * @method indexOf(, [fromIndex]) - * @returns Number - * @extra [fromIndex] is the index from which to begin the search. - * This method performs a simple strict equality comparison on . - * It does not support enhanced functionality such as searching - * the contents against a regex, callback, or deep comparison of objects. - * For such functionality, use the %findIndex% method instead. - * @example - * - * [1,2,3].indexOf(3) -> 1 - * [1,2,3].indexOf(7) -> -1 - * - ***/ - indexOf(search: any, fromIndex?: number): number; - - /*** - * @short Returns an array containing the elements all arrays have in common. - * @method intersect([a1], [a2], ...) - * @returns Array - * @extra This method will also correctly operate on arrays of objects. - * @example - * - * [1,3,5].intersect([5,7,9]) -> [5] - * ['a','b'].intersect('b','c') -> ['b'] - * - ***/ - intersect(...args: number[]): number[]; - intersect(...args: string[]): string[]; - intersect(...args: Object[]): Object[]; - intersect(...args: any[]): any[]; - - /*** - * @short Returns true if the array is empty. - * @method isEmpty() - * @returns Boolean - * @extra This is true if the array has a length of zero, or contains - * only %undefined%, %null%, or %NaN%. - * @example - * - * [].isEmpty() -> true - * [null,undefined].isEmpty() -> true - * - ***/ - isEmpty(): bool; - - /*** - * @short Returns the last element(s) in the array. - * @method last([num] = 1) - * @returns Mixed - * @extra When is passed, returns the last elements in the array. - * @example - * - * [1,2,3].last() -> 3 - * [1,2,3].last(2) -> [2,3] - * - ***/ - last(): any; - last(num: number): any[]; - - /*** - * @short Searches the array and returns the last index where occurs, - * or -1 if the element is not found. - * @method lastIndexOf(, [fromIndex]) - * @returns Number - * @extra [fromIndex] is the index from which to begin the search. - * This method performs a simple strict equality comparison on . - * @example - * - * [1,2,1].lastIndexOf(1) -> 2 - * [1,2,1].lastIndexOf(7) -> -1 - * - ***/ - lastIndexOf(search: any, fromIndex?: number): number; - - /*** - * @short Returns the elements in the array with the least - * commonly occuring value. - * @method least([map]) - * @returns Array - * @extra [map] may be a function mapping the value to be checked or a - * string acting as a shortcut. - * @example - * - * [3,2,2].least() -> [3] - * ['fe','fo','fum'].least('length') -> ['fum'] - * [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].least(function(n) { - * return n.age; - * }); -> [{age:35,name:'ken'}] - * - ***/ - least(map: string): any[]; - least(map: (n: any) => any): any[]; - - /*** - * @short Maps the array to another array containing the values that - * are the result of calling on each element. - * @method map(, [scope]) - * @returns Array - * @extra [scope] is the %this% object. In addition to providing this method - * for browsers that don't support it natively, this enhanced method - * also directly accepts a string, which is a shortcut for a function - * that gets that property (or invokes a function) on each element. - * @example - * - * [1,2,3].map(function(n) { - * return n * 3; - * }); -> [3,6,9] - * ['one','two','three'].map(function(n) { - * return n.length; - * }); -> [3,3,5] - * ['one','two','three'].map('length') -> [3,3,5] - ***/ - map(map: string, scope?: any): any[]; - map(map: (n: any) => any, scope?: any): any[]; - - /*** - * @short Returns the element in the array with the greatest value. - * @method max([map], [all] = false) - * @returns Mixed - * @extra [map] may be a function mapping the value to be checked or a string - * acting as a shortcut. If [all] is true, will return all max values - * in an array. - * @example - * - * [1,2,3].max() -> 3 - * ['fee','fo','fum'].max('length') -> 'fee' - * ['fee','fo','fum'].max('length', true) -> ['fee'] - + [{a:3,a:2}].max(function(n) { - * return n['a']; - * }); -> {a:3} - * - ***/ - max(map: string): any; - max(map: (n: any) => any): any; - - /*** - * @short Returns the element in the array with the lowest value. - * @method min([map], [all] = false) - * @returns Mixed - * @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut. If [all] is true, will return all min values in an array. - * @example - * - * [1,2,3].min() -> 1 - * ['fee','fo','fum'].min('length') -> 'fo' - * ['fee','fo','fum'].min('length', true) -> ['fo'] - + ['fee','fo','fum'].min(function(n) { - * return n.length; - * }); -> ['fo'] - + [{a:3,a:2}].min(function(n) { - * return n['a']; - * }); -> [{a:2}] - * - ***/ - min(map: string): any; - min(map: (n: any) => any): any; - - /*** - * @short Returns the elements in the array with the most - * commonly occuring value. - * @method most([map]) - * @returns Array - * @extra [map] may be a function mapping the value to be checked or a string - * acting as a shortcut. - * @example - * - * [3,2,2].most() -> [2] - * ['fe','fo','fum'].most('length') -> ['fe','fo'] - + [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].most(function(n) { - * return n.age; - * }); -> [{age:12,name:'bob'},{age:12,name:'ted'}] - * - ***/ - most(map: string): any[]; - most(map: (n: any) => any): any[]; - - /*** - * @short Returns true if none of the elements in the array match . - * @method none() - * @returns Boolean - * @extra will match a string, number, array, object, or alternately test - * against a function or regex. This method implements @array_matching. - * @example - * - * [1,2,3].none(5) -> true - * ['a','b','c'].none(/b/) -> false - + [{a:1},{b:2}].none(function(n) { - * return n['a'] > 1; - * }); -> true - * - ***/ - none(f: number): bool; - none(f: string): bool; - none(f: RegExp): bool; - none(f: Object): bool; - none(f: any[]): bool; - none(f: (n: any) => bool): bool; - - /*** - * @short Returns a copy of the array with the elements randomized. - * @method randomize() - * @returns Array - * @extra Uses Fisher-Yates algorithm. - * @example - * - * [1,2,3,4].randomize() -> [?,?,?,?] - * - ***/ - randomize(): any[]; - - /*** - * @short Reduces the array to a single result. - * @method reduce(, [init]) - * @returns Mixed - * @extra If [init] is passed as a starting value, that value will be passed - * as the first argument to the callback. The second argument will be - * the first element in the array. From that point, the result of the - * callback will then be used as the first argument of the next - * iteration. This is often refered to as "accumulation", and [init] - * is often called an "accumulator". If [init] is not passed, then - * will be called n - 1 times, where n is the length of the array. - * In this case, on the first iteration only, the first argument will - * be the first element of the array, and the second argument will be - * the second. After that callbacks work as normal, using the result - * of the previous callback as the first argument of the next. This - * method is only provided for those browsers that do not support it - * natively. - * - * @example - * - * [1,2,3,4].reduce(function(a, b) { - * return a - b; - * }); - * [1,2,3,4].reduce(function(a, b) { - * return a - b; - * }, 100); - * - ***/ - reduce(fn: (a: any, b: any) => any, init: any): any; - - /*** - * @short Identical to %Array#reduce%, - * but operates on the elements in reverse order. - * @method reduceRight([fn], [init]) - * @returns Mixed - * @extra This method is only provided for those browsers that do not support - * it natively. - * @example - * - * [1,2,3,4].reduceRight(function(a, b) { - * return a - b; - * }); - * - ***/ - reduceRight(fn: (a: any, b: any) => any, init: any): any; - - /*** - * @short Removes any element in the array that matches [f1], [f2], etc. - * @method remove([f1], [f2], ...) - * @returns Array - * @extra Will match a string, number, array, object, or alternately test - * against a function or regex. This method will change the array! - * Use %exclude% for a non-destructive alias. This method implements - * @array_matching. - * @example - * - * [1,2,3].remove(3) -> [1,2] - * ['a','b','c'].remove(/b/) -> ['a','c'] - + [{a:1},{b:2}].remove(function(n) { - * return n['a'] == 1; - * }); -> [{b:2}] - * - ***/ - remove(...args: number[]): number[]; - remove(...args: string[]): string[]; - remove(...args: Object[]): Object[]; - remove(...args: any[]): any[]; - remove(fn: (n: any) => bool): any[]; - - /*** - * @short Removes element at . If [end] is specified, removes the range - * between and [end]. This method will change the array! - * If you don't intend the array to be changed use %clone% first. - * @method removeAt(, [end]) - * @returns Array - * @example - * - * ['a','b','c'].removeAt(0) -> ['b','c'] - * [1,2,3,4].removeAt(1, 3) -> [1] - * - ***/ - removeAt(start: number, end?: number): any[]; - - /*** - * @short Returns a random element from the array. - * @method sample([num]) - * @returns Mixed - * @extra If [num] is passed, will return [num] samples from the array. - * @example - * - * [1,2,3,4,5].sample() -> // Random element - * [1,2,3,4,5].sample(3) -> // Array of 3 random elements - * - ***/ - sample(): any; - sample(num: number): any[]; - - /*** - * @short Returns true if any element in the array matches . - * @method some(, [scope]) - * @returns Boolean - * @extra [scope] is the %this% object. %any% is provided as an alias. - * In addition to providing this method for browsers that don't - * support it natively, this method also implements @array_matching. - * @example - * - * ['a','b','c'].some(function(n) { - * return n == 'a'; - * }); - * ['a','b','c'].some(function(n) { - * return n == 'd'; - * }); - * ['a','b','c'].some('a') -> true - * [{a:2},{b:5}].some({a:2}) -> true - ***/ - some(f: number, scope?: any): bool; - some(f: string, scope?: any): bool; - some(f: any, scope?: any): bool; - some(f: (n: any) => bool, scope?: any): bool; - - /*** - * @short Sorts the array by . - * @method sortBy(, [desc] = false) - * @returns Array - * @extra may be a function, a string acting as a shortcut, or blank - * (direct comparison of array values). [desc] will sort the array in - * descending order. When the field being sorted on is a string, the - * resulting order will be determined by an internal collation algorithm - * that is optimized for major Western languages, but can be customized. - * For more information see @array_sorting. - * @example - * - * ['world','a','new'].sortBy('length') -> ['a','new','world'] - * ['world','a','new'].sortBy('length', true) -> ['world','new','a'] - * [{age:72},{age:13},{age:18}].sortBy(function(n) { - * return n.age; - * }); -> [{age:13},{age:18},{age:72}] - * - ***/ - sortBy(map: string, desc?: bool): any[]; - sortBy(fn: (n: any) => any, desc?: bool): any[]; - - /*** - * @short Subtracts from the array all elements in [a1], [a2], etc. - * @method subtract([a1], [a2], ...) - * @returns Array - * @extra This method will also correctly operate on arrays of objects. - * @example - * - * [1,3,5].subtract([5,7,9]) -> [1,3] - * [1,3,5].subtract([3],[5]) -> [1] - * ['a','b'].subtract('b','c') -> ['a'] - * - ***/ - subtract(...args: any[]): any[]; - - /*** - * @method sum([map]) - * @returns Number - * @short Sums all values in the array. - * @extra [map] may be a function mapping the value to be summed or a string - * acting as a shortcut. - * @example - * - * [1,2,2].sum() -> 5 - * [{age:35},{age:12},{age:12}].sum(function(n) { - * return n.age; - * }); -> 59 - * [{age:35},{age:12},{age:12}].sum('age') -> 59 - * - ***/ - sum(map: string): number; - sum(fn: (n: any) => number): number; - - /*** - * @short Returns a slice of the array up to . - * @method to() - * @returns Array - * @example - * - * [1,2,3].to(1) -> [1] - * [1,2,3].to(2) -> [1,2] - * - ***/ - to(index: number): any[]; - - /*** - * @short Returns an array containing all elements in all arrays with - * duplicates removed. - * @method union([a1], [a2], ...) - * @returns Array - * @extra This method will also correctly operate on arrays of objects. - * @example - * - * [1,3,5].union([5,7,9]) -> [1,3,5,7,9] - * ['a','b'].union(['b','c']) -> ['a','b','c'] - * - ***/ - union(array: any[]): any[]; - union(...args: any[]): any[]; - - /*** - * @short Removes all duplicate elements in the array. - * @method unique([map] = null) - * @returns Array - * @extra [map] may be a function mapping the value to be uniqued on or a - * string acting as a shortcut. This is most commonly used when you - * have a key that ensures the object's uniqueness, and don't need to - * check all fields. This method will also correctly operate on arrays - * of objects. - * @example - * - * [1,2,2,3].unique() -> [1,2,3] - * [{foo:'bar'},{foo:'bar'}].unique() -> [{foo:'bar'}] - + [{foo:'bar'},{foo:'bar'}].unique(function(obj){ - * return obj.foo; - * }); -> [{foo:'bar'}] - * [{foo:'bar'},{foo:'bar'}].unique('foo') -> [{foo:'bar'}] - * - ***/ - unique(map?: string): any[]; - unique(fn?: (obj: any) => any): any[]; - - /*** - * @short Merges multiple arrays together. - * @method zip([arr1], [arr2], ...) - * @returns Array - * @extra This method "zips up" smaller arrays into one large whose elements - * are "all elements at index 0", "all elements at index 1", etc. - * Useful when you have associated data that is split over separated - * arrays. If the arrays passed have more elements than the original - * array, they will be discarded. If they have fewer elements, the - * missing elements will filled with %null%. - * @example - * - * [1,2,3].zip([4,5,6]) -> [[1,2], [3,4], [5,6]] - * ['Martin','John'].zip(['Luther','F.'], ['King','Kennedy']) -> [['Martin','Luther','King'], ['John','F.','Kennedy']] - * - ***/ - zip(...arrays: any[]): any[][]; -} - -interface Object { - - /*** - * @short Creates a new object, equivalent to %new Object()% or %{}%, - * but with extended methods. - * @method Object.extended( = {}) - * @returns Extended object - * @extra See extended objects for more. - * @example - * - * Object.extended() - * Object.extended({ happy:true, pappy:false }).keys() -> ['happy','pappy'] - * Object.extended({ happy:true, pappy:false }).values() -> [true, false] - * - ***/ - extended(obj?: Object): Object; - - /*** - * @short Converts the query string of a URL into an object. - * @method Object.fromQueryString(, [deep] = true) - * @returns Object - * @extra If [deep] is %false%, conversion will only accept shallow params (ie. no object or arrays with %[]% syntax) as these are not universally supported. - * @example - * - * Object.fromQueryString('foo=bar&broken=wear') -> { foo: 'bar', broken: 'wear' } - * Object.fromQueryString('foo[]=1&foo[]=2') -> { foo: [1,2] } - * - ***/ - fromQueryString(str: string, deep?: bool): Object; - - /*** - * @short Returns true if is an object of that type. - * @method Object.is[Type]() - * @returns Boolean - * @extra %isObject% will return false on anything that is not an object - * literal, including instances of inherited classes. Note also - * that %isNaN% will ONLY return true if the object IS %NaN%. - * It does not mean the same as browser native %isNaN%, which returns - * true for anything that is "not a number". - * - * @set - * isArray - * isObject - * isBoolean - * isDate - * isFunction - * isNaN - * isNumber - * isString - * isRegExp - * - * @example - * - * Object.isArray([1,2,3]) -> true - * Object.isDate(3) -> false - * Object.isRegExp(/wasabi/) -> true - * Object.isObject({ broken:'wear' }) -> true - * - ***/ - isArray(): bool; - isArray(obj: any): bool; - isObject(): bool; - isObject(obj: any): bool; - isBoolean(): bool; - isBoolean(obj: any): bool; - isDate(): bool; - isDate(obj: any): bool; - isFunction(): bool; - isFunction(obj: any): bool; - isNaN(): bool; - isNaN(obj: any): bool; - isNumber(): bool; - isNumber(obj: any): bool; - isString(): bool; - isString(obj: any): bool; - isRegExp(): bool; - isRegExp(obj: any): bool; - - /*** - * @short Creates a clone (copy) of . - * @method clone( = {}, [deep] = false) - * @returns Cloned object - * @extra Default is a shallow clone, unless [deep] is true. %clone% - * is available as an instance method on extended objects. - * @example - * - * Object.clone({foo:'bar'}) -> { foo: 'bar' } - * Object.clone() -> {} - * Object.extended({foo:'bar'}).clone() -> { foo: 'bar' } - * - ***/ - clone(obj?: Object, deep?: bool): Object; - - /*** - * @short Enumerable methods in the Array package are also available to - * the Object class. They will perform their normal operations for - * every property in . - * @method [enumerable]() - * @returns Boolean - * @extra In cases where a callback is used, instead of %element, index%, - * the callback will instead be passed %key, value%. Enumerable methods - * are also available to extended objects as instance methods. - * - * @set - * each - * map - * any - * all - * none - * count - * find - * findAll - * reduce - * isEmpty - * sum - * average - * min - * max - * least - * most - * - * @example - * - * Object.any({foo:'bar'}, 'bar') -> true - * Object.extended({foo:'bar'}).any('bar') -> true - * Object.isEmpty({}) -> true - * Object.map({ fred: { age: 52 } }, 'age'); -> { fred: 52 } - * - ***/ - map(map: string): Object; - map(obj: Object, map: string): Object; - map(map: (key: string, value: any) => any): Object; - map(obj: Object, map: (key: string, value: any) => any): Object; - - any(map: string): bool; - any(obj: Object, map: string): bool; - any(map: (key: string, value: any) => bool): bool; - any(obj: Object, map: (key: string, value: any) => bool): bool; - - all(map: string): bool; - all(obj: Object, map: string): bool; - all(map: (key: string, value: any) => bool): bool; - all(obj: Object, map: (key: string, value: any) => bool): bool; - - none(map: string): bool; - none(obj: Object, map: string): bool; - none(map: (key: string, value: any) => bool): bool; - none(obj: Object, map: (key: string, value: any) => bool): bool; - - count(map: string): number; - count(obj: Object, map: string): number; - count(map: (key: string, value: any) => bool): number; - count(obj: Object, map: (key: string, value: any) => bool): number; - - find(map: string): any; - find(obj: Object, map: string): any; - find(map: (key: string, value: any) => bool): any; - find(obj: Object, map: (key: string, value: any) => bool): any; - - findAll(map: string): any[]; - findAll(obj: Object, map: string): any[]; - findAll(map: (key: string, value: any) => bool): any[]; - findAll(obj: Object, map: (key: string, value: any) => bool): any[]; - - reduce(map: string, init?: any): any; - reduce(obj: Object, map: string, init?: any): any; - reduce(map: (key: string, value: any) => any, init?: any): any; - reduce(obj: Object, map: (key: string, value: any) => any, init?: any): any; - - isEmpty(): bool; - isEmpty(obj: Object): bool; - - sum(map: string): number; - sum(obj: Object, map: string): number; - sum(map: (key: string, value: any) => number): number; - sum(obj: Object, map: (key: string, value: any) => number): number; - - average(map: string): number; - average(obj: Object, map: string): number; - average(map: (key: string, value: any) => number): number; - average(obj: Object, map: (key: string, value: any) => number): number; - - min(map: string): Object; - min(obj: Object, map: string): Object; - min(map: (key: string, value: any) => any): Object; - min(obj: Object, map: (key: string, value: any) => any): Object; - - max(map: string): Object; - max(obj: Object, map: string): Object; - max(map: (key: string, value: any) => any): Object; - max(obj: Object, map: (key: string, value: any) => any): Object; - - least(map: string): Object; - least(obj: Object, map: string): Object; - least(map: (key: string, value: any) => any): Object; - least(obj: Object, map: (key: string, value: any) => any): Object; - - most(map: string): Object; - most(obj: Object, map: string): Object; - most(map: (key: string, value: any) => any): Object; - most(obj: Object, map: (key: string, value: any) => any): Object; - - /*** - * @short Returns true if and are equal. - * @method equal(, ) - * @returns Boolean - * @extra %equal% in Sugar is "egal", meaning the values are equal - * if they are "not observably distinguishable". Note that on - * extended objects the name is %equals% for readability. - * @example - * - * Object.equal({a:2}, {a:2}) -> true - * Object.equal({a:2}, {a:3}) -> false - * Object.extended({a:2}).equals({a:3}) -> false - * - ***/ - equal(a: Object, b: Object): bool; - - /*** - * @short Checks if has using hasOwnProperty from Object.prototype. - * @method has(, ) - * @returns Boolean - * @extra This method is considered safer than %Object#hasOwnProperty% when - * using objects as hashes. See - * http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ - * for more. - * @example - * - * Object.has({ foo: 'bar' }, 'foo') -> true - * Object.has({ foo: 'bar' }, 'baz') -> false - * Object.has({ hasOwnProperty: true }, 'foo') -> false - * - ***/ - has(key: string): bool; - has(obj: Object, key: string): bool; - - /*** - * @short Returns an array containing the keys in . Optionally calls - * [fn] for each key. - * @method keys(, [fn]) - * @returns Array - * @extra This method is provided for browsers that don't support it natively, - * and additionally is enhanced to accept the callback [fn]. Returned - * keys are in no particular order. %keys% is available as an instance - * method on extended objects. - * @example - * - * Object.keys({ broken: 'wear' }) -> ['broken'] - * Object.keys({ broken: 'wear' }, function(key, value) { - * // Called once for each key. - * }); - * Object.extended({ broken: 'wear' }).keys() -> ['broken'] - * - ***/ - keys(): string[]; - keys(obj: Object, fn?: (key: string, value: any) => void ): string[]; - - /*** - * @short Merges all the properties of into . - * @method merge(, , [deep] = false, [resolve] = true) - * @returns Merged object - * @extra Merges are shallow unless [deep] is %true%. Properties of - * will win in the case of conflicts, unless [resolve] is %false%. - * [resolve] can also be a function that resolves the conflict. - * In this case it will be passed 3 arguments, %key%, %targetVal%, - * and %sourceVal%, with the context set to . This will allow - * you to solve conflict any way you want, ie. adding two numbers - * together, etc. %merge% is available as an instance method on - * extended objects. - * @example - * - * Object.merge({a:1},{b:2}) -> { a:1, b:2 } - * Object.merge({a:1},{a:2}, false, false) -> { a:1 } - + Object.merge({a:1},{a:2}, false, function(key, a, b) { - * return a + b; - * }); -> { a:3 } - * Object.extended({a:1}).merge({b:2}) -> { a:1, b:2 } - * - ***/ - merge(target: Object, source: Object, deep?: bool, resolve?: bool): Object; - merge(target: Object, source: Object, deep?: bool, resolve?: (key: string, targetVal: any, sourceVal: any) => any): Object; - - /*** - * @short Returns the number of properties in . - * @method size() - * @returns Number - * @extra %size% is available as an instance method on extended objects. - * @example - * - * Object.size({ foo: 'bar' }) -> 1 - * - ***/ - size(): number; - size(obj: Object): number; - - /*** - * @short Runs and returns . - * @method tap(, ) - * @returns Object - * @extra A string can also be used as a shortcut to a method. This method - * is used to run an intermediary function in the middle of method - * chaining. As a standalone method on the Object class it doesn't - * have too much use. The power of %tap% comes when using extended - * objects or modifying the Object prototype with Object.extend(). - * @example - * - * Object.extend(); - * [2,4,6].map(Math.exp).tap(function(arr) { - * arr.pop() - * }); - * [2,4,6].map(Math.exp).tap('pop').map(Math.round); -> [7,55] - * - ***/ - tap(fn: string): Object; - tap(fn: (...args: any[]) => any): Object; - tap(obj: Object, fn: string): Object; - tap(obj: Object, fn: (...args: any[]) => any): Object; - - /*** - * @short Returns an array containing the values in . - * Optionally calls [fn] for each value. - * @method values(, [fn]) - * @returns Array - * @extra Returned values are in no particular order. %values% is available - * as an instance method on extended objects. - * @example - * - * Object.values({ broken: 'wear' }) -> ['wear'] - * Object.values({ broken: 'wear' }, function(value) { - * // Called once for each value. - * }); - * Object.extended({ broken: 'wear' }).values() -> ['wear'] - * - ***/ - values(): any[]; - values(fn: (value: any) => any): any[]; - values(obj: Object): any[]; - values(obj: Object, fn: (value: any) => any): any[]; - - /*** - * @short Watches a property of and runs when it changes. - * @method watch(, , ) - * @returns Nothing - * @extra is passed three arguments: the property , the old value, - * and the new value. The return value of [fn] will be set as the new - * value. This method is useful for things such as validating or cleaning - * the value when it is set. Warning: this method WILL NOT work in - * browsers that don't support %Object.defineProperty%. This notably - * includes IE 8 and below, and Opera. This is the only method in Sugar - * that is not fully compatible with all browsers. %watch% is available - * as an instance method on extended objects. - * @example - * - * Object.watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) { - * // Will be run when the property 'foo' is set on the object. - * }); - * Object.extended().watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) { - * // Will be run when the property 'foo' is set on the object. - * }); - * - ***/ - watch(prop: string, fn: (prop: string, oldVal: any, newVal: any) => any): void; - watch(obj: Object, prop: string, fn: (prop: string, oldVal: any, newVal: any) => any): void; -} - -interface Function { - - /*** - * @short Creates a function that will execute after [num] calls. - * @method after([num] = 1) - * @returns Function - * @extra %after% is useful for running a final callback after a series of - * asynchronous operations, when the order in which the operations will - * complete is unknown. - * @example - * - * var fn = (function() { - * // Will be executed once only - * }).after(3); fn(); fn(); fn(); - * - ***/ - after(num?: number): Function; - - /*** - * @short Binds as the %this% object for the function when it is called. - * Also allows currying an unlimited number of parameters. - * @method bind(, [arg1], ...) - * @returns Function - * @extra "currying" means setting parameters ([arg1], [arg2], etc.) ahead of - * time so that they are passed when the function is called later. - * If you pass additional parameters when the function is actually - * called, they will be added will be added to the end of the curried - * parameters. This method is provided for browsers that don't support - * it internally. - * @example - * - + (function() { - * return this; - * }).bind('woof')(); -> returns 'woof'; function is bound with 'woof' as the this object. - * (function(a) { - * return a; - * }).bind(1, 2)(); -> returns 2; function is bound with 1 as the this object and 2 curried as the first parameter - * (function(a, b) { - * return a + b; - * }).bind(1, 2)(3); -> returns 5; function is bound with 1 as the this object, 2 curied as the first parameter and 3 passed as the second when calling the function - * - ***/ - bind(scope?: Object, ...args: any[]): Function; - - /*** - * @short Cancels a delayed function scheduled to be run. - * @method cancel() - * @returns Function - * @extra %delay%, %lazy%, %throttle%, and %debounce% can all set delays. - * @example - * - * (function() { - * alert('hay'); // Never called - * }).delay(500).cancel(); - * - ***/ - cancel(): Function; - - /*** - * @short Creates a "debounced" function that postpones its execution until - * after milliseconds have passed. - * @method debounce() - * @returns Function - * @extra This method is useful to execute a function after things have - * "settled down". A good example of this is when a user tabs quickly - * through form fields, execution of a heavy operation should happen - * after a few milliseconds when they have "settled" on a field. - * @example - * - * var fn = (function(arg1) { - * // called once 50ms later - * }).debounce(50); fn() fn() fn(); - * - ***/ - debounce(ms: number): Function; - - /*** - * @short Executes the function after milliseconds. - * @method delay([ms] = 0, [arg1], ...) - * @returns Function - * @extra Returns a reference to itself. %delay% is also a way to execute - * non-blocking operations that will wait until the CPU is free. - * Delayed functions can be canceled using the %cancel% method. - * Can also curry arguments passed in after . - * @example - * - * (function(arg1) { - * // called 1s later - * }).delay(1000, 'arg1'); - * - ***/ - delay(ms?: number, ...args: any[]): Function; - - /*** - * @short Returns a new version of the function which when called will have - * some of its arguments pre-emptively filled in, also known as "currying". - * @method fill(, , ...) - * @returns Function - * @extra Arguments passed to a "filled" function are generally appended to - * the curried arguments. However, if %undefined% is passed as any of - * the arguments to %fill%, it will be replaced, when the "filled" - * function is executed. This allows currying of arguments even when - * they occur toward the end of an argument list (the example - * demonstrates this much more clearly). - * @example - * - * var delayOneSecond = setTimeout.fill(undefined, 1000); - * delayOneSecond(function() { - * // Will be executed 1s later - * }); - * - ***/ - fill(...args: any[]): Function; - - /*** - * @short Creates a lazy function that, when called repeatedly, will queue - * execution and wait [ms] milliseconds to execute again. - * @method lazy([ms] = 1, [limit] = Infinity) - * @returns Function - * @extra Lazy functions will always execute as many times as they are called - * up to [limit], after which point subsequent calls will be ignored - * (if it is set to a finite number). Compare this to %throttle%, which - * will execute only once per [ms] milliseconds. %lazy% is useful when - * you need to be sure that every call to a function is executed, but - * in a non-blocking manner. Calling %cancel% on a lazy function will - * clear the entire queue. Note that [ms] can also be a fraction. - * @example - * - * (function() { - * // Executes immediately. - * }).lazy()(); - * (3).times(function() { - * // Executes 3 times, with each execution 20ms later than the last. - * }.lazy(20)); - * (100).times(function() { - * // Executes 50 times, with each execution 20ms later than the last. - * }.lazy(20, 50)); - * - ***/ - lazy(ms?: number, limit?: number): Function; - - /*** - * @short Creates a function that will execute only once and store the result. - * @method once() - * @returns Function - * @extra %once% is useful for creating functions that will cache the result of - * an expensive operation and use it on subsequent calls. Also it can be - * useful for creating initialization functions that only need to be run - * once. - * @example - * - * var fn = (function() { - * // Will be executed once only - * }).once(); fn(); fn(); fn(); - * - ***/ - once(): Function; - - /*** - * @short Creates a "throttled" version of the function that will only be - * executed once per milliseconds. - * @method throttle() - * @returns Function - * @extra This is functionally equivalent to calling %lazy% with a [limit] - * of %1%. %throttle% is appropriate when you want to make sure a - * function is only executed at most once for a given duration. - * Compare this to %lazy%, which will queue rapid calls and execute - * them later. - * @example - * - * (3).times(function() { - * // called only once. will wait 50ms until it responds again - * }.throttle(50)); - * - ***/ - throttle(ms: number): Function; -} - -interface RegExp { - - /*** - * @short Escapes all RegExp tokens in a string. - * @method RegExp.escape( = '') - * @returns String - * @example - * - * RegExp.escape('really?') -> 'really\?' - * RegExp.escape('yes.') -> 'yes\.' - * RegExp.escape('(not really)') -> '\(not really\)' - * - ***/ - escape(str: string): string; - - /*** - * @short Adds to the regex. - * @method addFlag() - * @returns RegExp - * @example - * - * /texty/.addFlag('g') -> now has global flag set - * - ***/ - addFlag(flag: string): RegExp; - - /*** - * @short Returns the flags of the regex as a string. - * @method getFlags() - * @returns String - * @example - * - * /texty/gim.getFlags('testy') -> 'gim' - * - ***/ - getFlags(): string; - - /*** - * @short Removes from the regex. - * @method removeFlag() - * @returns RegExp - * @example - * - * /texty/g.removeFlag('g') -> now has global flag removed - * - ***/ - removeFlag(flag: string): RegExp; - - /*** - * @short Sets the flags on a regex and retuns a copy. - * @method setFlags() - * @returns RegExp - * @example - * - * /texty/.setFlags('gim') -> now has global, ignoreCase, and multiline set - * - ***/ - setFlags(flags: string): RegExp; -} - -interface Locale { - plural: bool; - months: string; - weekdays: string; - units: string; - numbers: string; - tokens: string[]; - short: string; - long: string; - full: string; - past: string; - future: string; - duration: string; - timeMarker: string; - ampm: string; - modifiers: - { - name: string; - src: string; - value: number; - }[]; - dateParse: string[]; - timeParse: string[]; -} - -interface Date { - - /*** - * @short Adds a locale to the locales understood by Sugar. - * @method Date.addLocale(, ) - * @returns Locale - * @extra For more see @date_format. - ***/ - addLocale(code: string, set: Locale): Locale; - - /*** - * @short Alternate Date constructor which understands many different text formats, - * a timestamp, or another date. - * @method Date.create(, [locale] = currentLocale) - * @returns Date - * @extra If no argument is given, date is assumed to be now. %Date.create% additionally - * can accept enumerated parameters as with the standard date constructor. [locale] - * can be passed to specify the locale that the date is in. When unspecified, the - * current locale (default is English) is assumed. UTC-based dates can be created - * through the %utc% object. For more see @date_format. - * @set - * Date.utc.create - * - * @example - * - * Date.create('July') -> July of this year - * Date.create('1776') -> 1776 - * Date.create('today') -> today - * Date.create('wednesday') -> This wednesday - * Date.create('next friday') -> Next friday - * Date.create('July 4, 1776') -> July 4, 1776 - * Date.create(-446806800000) -> November 5, 1955 - * Date.create(1776, 6, 4) -> July 4, 1776 - * Date.create('1776å¹´07月04æ—¥', 'ja') -> July 4, 1776 - * Date.utc.create('July 4, 1776', 'en') -> July 4, 1776 - * - ***/ - create(locale?: string): Date; - create(d: string, locale?: string): Date; - create(year: number, month: number, day: number, locale?: string): Date; - - /*** - * @short Alternate form of %Date.create% with any ambiguity assumed to be the future. - * @method Date.future(, [locale] = currentLocale) - * @returns Date - * @extra For example %"Sunday"% can be either "the Sunday coming up" or "the Sunday last" - * depending on context. Note that dates explicitly in the past ("last Sunday") will - * remain in the past. This method simply provides a hint when ambiguity exists. UTC - * -based dates can be created through the %utc% object. For more, see @date_format. - * @set - * Date.utc.future - * - * @example - * - * Date.future('July') -> July of this year or next depending on the current month - * Date.future('Wednesday') -> This wednesday or next depending on the current weekday - * - ***/ - future(d: string, locale?: string): Date; - - /*** - * @short Gets the locale for the given code, or the current locale. - * @method Date.getLocale([code] = current) - * @returns Locale - * @extra The resulting locale object can be manipulated to provide more control over date localizations. - * For more about locales, see @date_format. - ***/ - getLocale(code?: string): Locale; - - /*** - * @short Returns the number of milliseconds since January 1st, 1970 00:00:00 (UTC time). - * @method Date.now() - * @returns String - * @extra Provided for browsers that do not support this method. - * @example - * - * Date.now() -> ex. 1311938296231 - * - ***/ - now(): string; - - /*** - * @short Alternate form of %Date.create% with any ambiguity assumed to be the past. - * @method Date.past(, [locale] = currentLocale) - * @returns Date - * @extra For example %"Sunday"% can be either "the Sunday coming up" or "the Sunday last" depending - * on context. Note that dates explicitly in the future ("next Sunday") will remain in the future. - * This method simply provides a hint when ambiguity exists. UTC-based dates can be created - * through the %utc% object. For more, see @date_format. - * @set - * Date.utc.past - * @example - * - * Date.past('July') -> July of this year or last depending on the current month - * Date.past('Wednesday') -> This wednesday or last depending on the current weekday - * - ***/ - past(d: string, local?: string): Date; - - /*** - * @short Creates a new date range. - * @method Date.range([start], [end]) - * @returns DateRange - * @extra If either [start] or [end] are null, they will default to the current date. - ***/ - range(start: Date, end: Date): DateRange; - - /*** - * @short Sets the current locale to be used with dates. - * @method Date.setLocale() - * @returns Locale - * @extra Sugar has support for 13 locales that are available through the - & "Date Locales" package. In addition you can define a new locale with - * %Date.addLocale%. For more see @date_format. - * - ***/ - setLocale(code: string): Locale; - - /*** - * @short Adds of the unit to the date. If [reset] is true, all lower - * units will be reset. - * @method add[Units](, [reset] = false) - * @returns Date - * @extra Note that "months" is ambiguous as a unit of time. If the target - * date falls on a day that does not exist (ie. August 31 -> February 31), - * the date will be shifted to the last day of the month. Don't use - * %addMonths% if you need precision. - * - * @set - * addMilliseconds - * addSeconds - * addMinutes - * addHours - * addDays - * addWeeks - * addMonths - * addYears - * - * @example - * - * Date.create().addMilliseconds(5) -> current time + 5 milliseconds - * Date.create().addDays(5) -> current time + 5 days - * Date.create().addYears(5) -> current time + 5 years - * - ***/ - addMilliseconds(num: number, reset?: bool): Date; - addSeconds(num: number, reset?: bool): Date; - addMinutes(num: number, reset?: bool): Date; - addHours(num: number, reset?: bool): Date; - addDays(num: number, reset?: bool): Date; - addWeeks(num: number, reset?: bool): Date; - addMonths(num: number, reset?: bool): Date; - addYears(num: number, reset?: bool): Date; - - /*** - * @short Sets the date forward. - * @method advance(, [reset] = false) - * @returns Date - * @extra This method can accept multiple formats including an object, a string - * in the format %3 days%, a single number as milliseconds, or enumerated - * parameters (as with the Date constructor). If [reset] is %true%, any - * units more specific than those passed will be reset. For more see - * @date_format. - * @example - * - * new Date().advance({ year: 2 }) -> 2 years in the future - * new Date().advance('2 days') -> 2 days in the future - * new Date().advance(0, 2, 3) -> 2 months 3 days in the future - * new Date().advance(86400000) -> 1 day in the future - * - ***/ - advance(set: string, reset?: bool): Date; - advance(year: number, month: number, day: number, reset?: bool): Date; - advance(milliseconds: number, reset?: bool): Date; - advance(set: Object, reset?: bool): Date; - - /*** - * @short Sets the date to the beginning of the appropriate unit. - * @method beginningOf[Unit]() - * @returns Date - * - * @set - * beginningOfDay - * beginningOfWeek - * beginningOfMonth - * beginningOfYear - * - * @example - * - * Date.create().beginningOfDay() -> the beginning of today (resets the time) - * Date.create().beginningOfWeek() -> the beginning of the week - * Date.create().beginningOfMonth() -> the beginning of the month - * Date.create().beginningOfYear() -> the beginning of the year - * - ***/ - beginningOfDay(): Date; - beginningOfWeek(): Date; - beginningOfMonth(): Date; - beginningOfYear(): Date; - - /*** - * @short Clones the date. - * @method clone() - * @returns Date - * @example - * - * Date.create().clone() -> Copy of now - * - ***/ - clone(): Date; - - /*** - * @short Returns the number of days in the date's month. - * @method daysInMonth() - * @returns Number - * @example - * - * Date.create('May').daysInMonth() -> 31 - * Date.create('February, 2000').daysInMonth() -> 29 - * - ***/ - daysInMonth(): number; - - /*** - * @short Sets the date to the end of the appropriate unit. - * @method endOf[Unit]() - * @returns Date - * - * @set - * endOfDay - * endOfWeek - * endOfMonth - * endOfYear - * - * @example - * - * Date.create().endOfDay() -> the end of today (sets the time to 23:59:59.999) - * Date.create().endOfWeek() -> the end of the week - * Date.create().endOfMonth() -> the end of the month - * Date.create().endOfYear() -> the end of the year - * - ***/ - endOfDay(): Date; - endOfWeek(): Date; - endOfMonth(): Date; - endOfYear(): Date; - - /*** - * @short Formats and outputs the date. - * @method format(, [locale] = currentLocale) - * @returns String - * @extra can be a number of pre-determined formats or a string of - * tokens. Locale-specific formats are %short%, %long%, and %full% which - * have their own aliases and can be called with %date.short()%, etc. - * If is not specified the %long% format is assumed. [locale] - * specifies a locale code to use (if not specified the current locale - * is used). See @date_format for more details. - * - * @set - * short - * long - * full - * - * @example - * - * Date.create().format() -> ex. July 4, 2003 - * Date.create().format('{Weekday} {d} {Month}, {yyyy}') -> ex. Monday July 4, 2003 - * Date.create().format('{hh}:{mm}') -> ex. 15:57 - * Date.create().format('{12hr}:{mm}{tt}') -> ex. 3:57pm - * Date.create().format(Date.ISO8601_DATETIME) -> ex. 2011-07-05 12:24:55.528Z - * Date.create('last week').format('short', 'ja') -> ex. 先週 - * Date.create('yesterday').format(function(value,unit,ms,loc) { - * // value = 1, unit = 3, ms = -86400000, loc = [current locale object] - * }); -> ex. 1 day ago - * - ***/ - format(format: string, locale?: string): string; - short(): string; - long(): string; - full(): string; - - /*** - * @short Returns a string representation of the offset from UTC time. If [iso] - * is true the offset will be in ISO8601 format. - * @method getUTCOffset([iso]) - * @returns String - * @example - * - * new Date().getUTCOffset() -> "+0900" - * new Date().getUTCOffset(true) -> "+09:00" - * - ***/ - getUTCOffset(iso?: bool): string; - - /*** - * @short Gets the date's week (of the year). - * @method getWeek() - * @returns Number - * @extra If %utc% is set on the date, the week will be according to UTC time. - * - * @example - * - * new Date().getWeek() -> today's week of the year - * - ***/ - getWeek(): number; - - /*** - * @short Alias for %getDay%. - * @method getWeekday() - * @returns Number - * @set - * getUTCWeekday - * - * @example - * - * Date.create().getWeekday(); -> (ex.) 3 - * Date.create().getUTCWeekday(); -> (ex.) 3 - * - ***/ - getWeekday(): number; - getUTCWeekday(): number; - // Duplicate from lib.d.ts - // getDay(): number; - // Duplicate from lib.d.ts - // getUTCDay(): number; - - /*** - * @short Returns true if the date is . - * @method is(, [margin] = 0) - * @returns Boolean - * @extra will accept a date object, timestamp, or text format. %is% - * additionally understands more generalized expressions like - * month/weekday names, 'today', etc, and compares to the precision - * implied in . [margin] allows an extra margin of error in - * milliseconds. For more, see @date_format. - * @example - * - * Date.create().is('July') -> true or false? - * Date.create().is('1776') -> false - * Date.create().is('today') -> true - * Date.create().is('weekday') -> true or false? - * Date.create().is('July 4, 1776') -> false - * Date.create().is(-6106093200000) -> false - * Date.create().is(new Date(1776, 6, 4)) -> false - * - ***/ - is(d: string, margin?: number): bool; - is(milliseconds: number, margin?: number): bool; - is(d: Date, margin?: number): bool; - - /*** - * @short Returns true if the date is after the . - * @method isAfter(, [margin] = 0) - * @returns Boolean - * @extra [margin] is to allow extra margin of error (in ms). will accept - * a date object, timestamp, or text format. If not specified, is - * assumed to be now. See @date_format for more. - * @example - * - * new Date().isAfter('tomorrow') -> false - * new Date().isAfter('yesterday') -> true - * - ***/ - isAfter(d: string, margin?: number): bool; - isAfter(milliseconds: number, margin?: number): bool; - isAfter(d: Date, margin?: number): bool; - - /*** - * @short Returns true if the date is before . - * @method isBefore(, [margin] = 0) - * @returns Boolean - * @extra [margin] is to allow extra margin of error (in ms). will accept - * a date object, timestamp, or text format. If not specified, is - * assumed to be now. See @date_format for more. - * @example - * - * new Date().isBefore('tomorrow') -> true - * new Date().isBefore('yesterday') -> false - * - ***/ - isBefore(d: string, margin?: number): bool; - isBefore(milliseconds: number, margin?: number): bool; - isBefore(d: Date, margin?: number): bool; - - /*** - * @short Returns true if the date falls between and . - * @method isBetween(, , [margin] = 0) - * @returns Boolean - * @extra [margin] is to allow extra margin of error (in ms). and - * will accept a date object, timestamp, or text format. If not specified, - * they are assumed to be now. See @date_format for more. - * @example - * - * new Date().isBetween('yesterday', 'tomorrow') -> true - * new Date().isBetween('last year', '2 years ago') -> false - * - ***/ - isBefore(start: string, end: string, margin?: number): bool; - isBefore(start: number, end: string, margin?: number): bool; - isBefore(start: Date, end: Date, margin?: number): bool; - - /*** - * @short Returns true if the date falls on that day. - * @method is[Day]() - * @returns Boolean - * @extra Also available: %isYesterday%, %isToday%, %isTomorrow%, %isWeekday%, - * and %isWeekend%. - * - * @set - * isToday - * isYesterday - * isTomorrow - * isWeekday - * isWeekend - * isSunday - * isMonday - * isTuesday - * isWednesday - * isThursday - * isFriday - * isSaturday - * - * @example - * - * Date.create('tomorrow').isToday() -> false - * Date.create('thursday').isTomorrow() -> ? - * Date.create('yesterday').isWednesday() -> ? - * Date.create('today').isWeekend() -> ? - * - ***/ - isToday(): bool; - isYesterday(): bool; - isTomorrow(): bool; - isWeekday(): bool; - isWeekend(): bool; - isSunday(): bool; - isMonday(): bool; - isTuesday(): bool; - isWednesday(): bool; - isThursday(): bool; - isFriday(): bool; - isSaturday(): bool; - - /*** - * @short Returns true if the date is in the future. - * @method isFuture() - * @returns Boolean - * @example - * - * Date.create('next week').isFuture() -> true - * Date.create('last week').isFuture() -> false - * - ***/ - isFuture(): bool; - - /*** - * @short Returns true if the date is last week/month/year. - * @method isLast[Unit]() - * @returns Boolean - * - * @set - * isLastWeek - * isLastMonth - * isLastYear - * - * @example - * - * Date.create('yesterday').isLastWeek() -> true or false? - * Date.create('yesterday').isLastMonth() -> probably not... - * Date.create('yesterday').isLastYear() -> even less likely... - * - ***/ - isLastWeek(): bool; - isLastMonth(): bool; - isLastYear(): bool; - - /*** - * @short Returns true if the date is a leap year. - * @method isLeapYear() - * @returns Boolean - * @example - * - * Date.create('2000').isLeapYear() -> true - * - ***/ - isLeapYear(): bool; - - /*** - * @short Returns true if the date is next week/month/year. - * @method isNext[Unit]() - * @returns Boolean - * - * @set - * isNextWeek - * isNextMonth - * isNextYear - * - * @example - * - * Date.create('tomorrow').isNextWeek() -> true or false? - * Date.create('tomorrow').isNextMonth() -> probably not... - * Date.create('tomorrow').isNextYear() -> even less likely... - * - ***/ - isNextWeek(): bool; - isNextMonth(): bool; - isNextYear(): bool; - - /*** - * @short Returns true if the date is in the past. - * @method isPast() - * @returns Boolean - * @example - * - * Date.create('last week').isPast() -> true - * Date.create('next week').isPast() -> false - * - ***/ - isPast(): bool; - - /*** - * @short Returns true if the date is this week/month/year. - * @method isThis[Unit]() - * @returns Boolean - * - * @set - * isThisWeek - * isThisMonth - * isThisYear - * - * @example - * - * Date.create('tomorrow').isThisWeek() -> true or false? - * Date.create('tomorrow').isThisMonth() -> probably... - * Date.create('tomorrow').isThisYear() -> signs point to yes... - * - ***/ - isThisWeek(): bool; - isThisMonth(): bool; - isThisYear(): bool; - - /*** - * @short Returns true if the date has no timezone offset. - * @method isUTC() - * @returns Boolean - * @extra This will also return true for a date that has had %toUTC% called on it. This is intended to help approximate shifting timezones which is not possible in client-side Javascript. Note that the native method %getTimezoneOffset% will always report the same thing, even if %isUTC% becomes true. - * @example - * - * new Date().isUTC() -> true or false? - * new Date().toUTC().isUTC() -> true - * - ***/ - isUTC(): bool; - - /*** - * @short Returns true if the date is valid. - * @method isValid() - * @returns Boolean - * @example - * - * new Date().isValid() -> true - * new Date('flexor').isValid() -> false - * - ***/ - isValid(): bool; - - /*** - * @method iso() - * @method toISOString() - * @returns String - * @short Formats the string to ISO8601 format. - * @extra This will always format as UTC time. Provided for browsers that do not - * support this method. - * @example - * - * Date.create().toISOString() -> ex. 2011-07-05 12:24:55.528Z - * - ***/ - iso(): string; - // Duplicate from lib.d.ts - // toISOString(): string; - - /*** - * @short Returns a relative date string offset to the current time. - * @method relative([fn], [locale] = currentLocale) - * @returns String - * @extra [fn] can be passed to provide for more granular control over the - * resulting string. [fn] is passed 4 arguments: the adjusted value, - * unit, offset in milliseconds, and a localization object. As an - * alternate syntax, [locale] can also be passed as the first (and only) - * parameter. For more, see @date_format. - * @example - * - * Date.create('90 seconds ago').relative() -> 1 minute ago - * Date.create('January').relative() -> ex. 5 months ago - * Date.create('January').relative('ja') -> 3ãƒ¶æœˆå‰ - * Date.create('120 minutes ago').relative(function(val,unit,ms,loc) { - * // value = 2, unit = 3, ms = -7200, loc = [current locale object] - * }); -> ex. 5 months ago - * - ***/ - relative(locale: string): string; - relative(fn?: (value: number, unit: string, ms:number, loc: Locale) => string, locale?: string): string; - - /*** - * @short Resets the unit passed and all smaller units. Default is "hours", - * effectively resetting the time. - * @method reset([unit] = 'hours') - * @returns Date - * @example - * - * Date.create().reset('day') -> Beginning of today - * Date.create().reset('month') -> 1st of the month - * - ***/ - reset(unit?: string): Date; - - /*** - * @short Sets the date back. - * @method rewind(, [reset] = false) - * @returns Date - * @extra This method can accept multiple formats including a single number as a - * timestamp, an object, or enumerated parameters (as with the Date - * constructor). If [reset] is %true%, any units more specific than - * those passed will be reset. For more see @date_format. - * @example - * - * new Date().rewind({ year: 2 }) -> 2 years in the past - * new Date().rewind(0, 2, 3) -> 2 months 3 days in the past - * new Date().rewind(86400000) -> 1 day in the past - * - ***/ - rewind(ms: number, reset?: bool): Date; - rewind(year: number, month: number, day: number, reset?: bool): Date; - //rewind(d: Object, reset?: bool): Date; // Do not like this, is not typesafe - - /*** - * @short Sets the date object. - * @method set(, [reset] = false) - * @returns Date - * @extra This method can accept multiple formats including a single number as a - * timestamp, an object, or enumerated parameters (as with the Date - * constructor). If [reset] is %true%, any units more specific than those - * passed will be reset. - * - * @example - * - * new Date().set({ year: 2011, month: 11, day: 31 }) -> December 31, 2011 - * new Date().set(2011, 11, 31) -> December 31, 2011 - * new Date().set(86400000) -> 1 day after Jan 1, 1970 - * new Date().set({ year: 2004, month: 6 }, true) -> June 1, 2004, 00:00:00.000 - * - ***/ - set(ms: number): Date; - set(year: number, month: number, day: number): Date; - //set(d: Object, reset?: bool): Date; // Do not like this, is not typesafe - - - /*** - * @short Sets the week (of the year). - * @method setWeek() - * @returns Nothing - * - * @example - * - * d = new Date(); d.setWeek(15); d; -> 15th week of the year - * - ***/ - setWeek(week: number): void; - - /*** - * @short Sets the weekday of the date. - * @method setWeekday() - * @returns Nothing - * - * @example - * - * d = new Date(); d.setWeekday(1); d; -> Monday of this week - * d = new Date(); d.setWeekday(6); d; -> Saturday of this week - * - ***/ - setWeekday(day: number): void; - - /*** - * @short Returns a JSON representation of the date. - * @method toJSON() - * @returns String - * @extra This is effectively an alias for %toISOString%. Will always return - * the date in UTC time. Provided for browsers that do not support this - * method. - * @example - * - * Date.create().toJSON() -> ex. 2011-07-05 12:24:55.528Z - * - ***/ - toJSON(): string; - - /*** - * @short Returns the time ago in the appropriate unit. - * @method [units]Ago() - * @returns Number - * - * @set - * millisecondsAgo - * secondsAgo - * minutesAgo - * hoursAgo - * daysAgo - * weeksAgo - * monthsAgo - * yearsAgo - * - * @example - * - * Date.create('last year').millisecondsAgo() -> 3,600,000 - * Date.create('last year').daysAgo() -> 7 - * Date.create('last year').yearsAgo() -> 15 - * - ***/ - millisecondsAgo(): number; - secondsAgo(): number; - minutesAgo(): number; - hoursAgo(): number; - daysAgo(): number; - weeksAgo(): number; - monthsAgo(): number; - yearsAgo(): number; - - /*** - * @short Returns the time from now in the appropriate unit. - * @method [units]FromNow() - * @returns Number - * - * @set - * millisecondsFromNow - * secondsFromNow - * minutesFromNow - * hoursFromNow - * daysFromNow - * weeksFromNow - * monthsFromNow - * yearsFromNow - * - * @example - * - * Date.create('next year').millisecondsFromNow() -> 3,600,000 - * Date.create('next year').daysFromNow() -> 7 - * Date.create('next year').yearsFromNow() -> 15 - * - ***/ - millisecondsFromNow(): number; - secondsFromNow(): number; - minutesFromNow(): number; - hoursFromNow(): number; - daysFromNow(): number; - weeksFromNow(): number; - monthsFromNow(): number; - yearsFromNow(): number; - - /*** - * @short Returns the time since [d] in the appropriate unit. - * @method [units]Since([d], [locale] = currentLocale) - * @returns Number - * @extra [d] will accept a date object, timestamp, or text format. If not - * specified, [d] is assumed to be now. [locale] can be passed to specify - * the locale that the date is in. %[unit]Ago% is provided as an alias to - * make this more readable when [d] is assumed to be the current date. - * For more see @date_format. - * - * @set - * millisecondsSince - * secondsSince - * minutesSince - * hoursSince - * daysSince - * weeksSince - * monthsSince - * yearsSince - * - * @example - * - * Date.create().millisecondsSince('1 hour ago') -> 3,600,000 - * Date.create().daysSince('1 week ago') -> 7 - * Date.create().yearsSince('15 years ago') -> 15 - * Date.create('15 years ago').yearsAgo() -> 15 - * - ***/ - millisecondsSince(date?: Date, locale?: string): number; - millisecondsSince(date: string, locale?: string): number; - secondsSince(date?: Date, locale?: string): number; - secondsSince(date: string, locale?: string): number; - minutesSince(date?: Date, locale?: string): number; - minutesSince(date: string, locale?: string): number; - hoursSince(date?: Date, locale?: string): number; - hoursSince(date: string, locale?: string): number; - daysSince(date?: Date, locale?: string): number; - daysSince(date: string, locale?: string): number; - weeksSince(date?: Date, locale?: string): number; - weeksSince(date: string, locale?: string): number; - monthsSince(date?: Date, locale?: string): number; - monthsSince(date: string, locale?: string): number; - yearsSince(date?: Date, locale?: string): number; - yearsSince(date: string, locale?: string): number; - - /*** - * @short Returns the time until [d] in the appropriate unit. - * @method [units]Until([d], [locale] = currentLocale) - * @returns Number - * @extra [d] will accept a date object, timestamp, or text format. If not - * specified, [d] is assumed to be now. [locale] can be passed to specify - * the locale that the date is in. %[unit]FromNow% is provided as an - * alias to make this more readable when [d] is assumed to be the current - * date. For more see @date_format. - * - * @set - * millisecondsUntil - * secondsUntil - * minutesUntil - * hoursUntil - * daysUntil - * weeksUntil - * monthsUntil - * yearsUntil - * - * @example - * - * Date.create().millisecondsUntil('1 hour from now') -> 3,600,000 - * Date.create().daysUntil('1 week from now') -> 7 - * Date.create().yearsUntil('15 years from now') -> 15 - * Date.create('15 years from now').yearsFromNow() -> 15 - * - ***/ - millisecondsUntil(date?: Date, locale?: string): number; - millisecondsUntil(date: string, locale?: string): number; - secondsUntil(date?: Date, locale?: string): number; - secondsUntil(date: string, locale?: string): number; - minutesUntil(date?: Date, locale?: string): number; - minutesUntil(date: string, locale?: string): number; - hoursUntil(date?: Date, locale?: string): number; - hoursUntil(date: string, locale?: string): number; - daysUntil(date?: Date, locale?: string): number; - daysUntil(date: string, locale?: string): number; - weeksUntil(date?: Date, locale?: string): number; - weeksUntil(date: string, locale?: string): number; - monthsUntil(date?: Date, locale?: string): number; - monthsUntil(date: string, locale?: string): number; - yearsUntil(date?: Date, locale?: string): number; - yearsUntil(date: string, locale?: string): number; - - /*** - * @short Sets the internal utc flag for the date. When on, UTC-based methods - * will be called internally. - * @method utc([on] = true) - * @returns Date - * @extra For more see @date_format. - * @example - * - * new Date().utc(true) - * new Date().utc(false) - * - ***/ - utc(on?: bool): Date; -} - -/*** -* @package DateRange -* @dependency date -* @description Date Ranges define a range of time. They can enumerate over specific points -* within that range, and be manipulated and compared. -* -***/ -interface DateRange { - start: Date; - end: Date; - - /*** - * @short Returns true if is contained inside the DateRange. - * may be a date or another DateRange. - * @method contains() - * @returns Boolean - * @example - * - * Date.range('2003', '2005').contains(Date.create('2004')) -> true - * - ***/ - contains(d: Date): bool; - contains(d: DateRange): bool; - - /*** - * @short Return the duration of the DateRange in milliseconds. - * @method duration() - * @returns Number - * @example - * - * Date.range('2003', '2005').duration() -> 94694400000 - * - ***/ - duration(): number; - - /*** - * @short Increments through the date range for each [unit], calling [fn] if it is passed. - * Returns an array of each increment visited. - * @method each[Unit]([fn]) - * @returns Date - * - * @set - * eachMillisecond - * eachSecond - * eachMinute - * eachHour - * eachDay - * eachWeek - * eachMonth - * eachYear - * - * @example - * - * Date.range('2003-01', '2003-02').eachMonth() -> [...] - * Date.range('2003-01-15', '2003-01-16').eachDay() -> [...] - * - ***/ - eachMillisecond(fn?: (d: Date) => void): Date[]; - eachSecond(fn?: (d: Date) => void): Date[]; - eachMinute(fn?: (d: Date) => void): Date[]; - eachHour(fn?: (d: Date) => void): Date[]; - eachDay(fn?: (d: Date) => void): Date[]; - eachWeek(fn?: (d: Date) => void): Date[]; - eachMonth(fn?: (d: Date) => void): Date[]; - eachYear(fn?: (d: Date) => void): Date[]; - - /*** - * @short Iterates through the DateRange for every , - * calling [fn] if it is passed. Returns an array of each increment visited. - * @method every(, [fn]) - * @returns Array - * @extra When is a number, increments will be to the exact millisecond. - * can also be a string in the format %{number} {unit}s%, in which - * case it will increment in the unit specified. Note that a discrepancy exists - * in the case of months, as %(2).months()% is an approximation. Stepping - * through the actual months by passing %"2 months"% is usually preferable in - * this case. - * @example - * - * Date.range('2003-01', '2003-03').every("2 months") -> [...] - * - ***/ - every(ms: number, fn?: (d: Date) => void): Date[]; - every(increment: string, fn?: (d: Date) => void): Date[]; - - /*** - * @short Returns a new DateRange with the latest starting point as its start, and the - * earliest ending point as its end. If the two ranges do not intersect this will - * effectively produce an invalid range. - * @method intersect() - * @returns DateRange - * @example - * - * Date.range('2003-01', '2005-01').intersect(Date.range('2004-01', '2006-01')) -> Jan 1, 2004..Jan 1, 2005 - * - ***/ - intersect(range: DateRange): DateRange; - - /*** - * @short Returns true if the DateRange is valid, false otherwise. - * @method isValid() - * @returns Boolean - * @example - * - * Date.range('2003', '2005').isValid() -> true - * Date.range('2005', '2003').isValid() -> false - * - ***/ - isValid(): bool; - - /*** - * @short Returns a string representation of the DateRange. - * @method toString() - * @returns String - * @example - * - * Date.range('2003', '2005').toString() -> January 1, 2003..January 1, 2005 - * - ***/ - toString(): string; - - /*** - * @short Returns a new DateRange with the earliest starting point as its start, - * and the latest ending point as its end. If the two ranges do not intersect - * this will effectively remove the "gap" between them. - * @method union() - * @returns DateRange - * @example - * - * Date.range('2003=01', '2005-01').union(Date.range('2004-01', '2006-01')) -> Jan 1, 2003..Jan 1, 2006 - * - ***/ - union(range: DateRange): DateRange; -} +/* +sugar-1.3.9.d.ts may be freely distributed under the MIT license. + +Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/sugar.d.ts + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*/ + +interface String { + + /** + * Adds at [index].
Negative values are also allowed. + * @param str String to add. + * @param index Index where is added. Default = str.length + * @returns Original string with added at [index]. + * @extra %insert% is provided as an alias, and is generally more readable when using an index. + * @example + * 'schfifty'.add(' five') -> schfifty five + * 'dopamine'.insert('e', 3) -> dopeamine + * 'spelling eror'.insert('r', -3) -> spelling error + **/ + add(str: string, index?: number): string; + + /** + * @see add + **/ + insert(str: string, index?: number): string; + + /** + * Assigns variables to tokens in a string. + * @param objs Variable tokens to assign in the string. + * @returns String with assigned to variables in the original string. + * @extra If an object is passed, it's properties can be assigned using + * the object's keys. If a non-object (string, number, etc.) + * is passed it can be accessed by the argument number beginning + * with 1 (as with regex tokens). Multiple objects can be passed + * and will be merged together (original objects are unaffected). + * @example + * 'Welcome, Mr. {name}.'.assign({ name: 'Franklin' }) -> 'Welcome, Mr. Franklin.' + * 'You are {1} years old today.'.assign(14) -> 'You are 14 years old today.' + * '{n} and {r}'.assign({ n: 'Cheech' }, { r: 'Chong' }) -> 'Cheech and Chong' + **/ + assign(...objs: any[]): string; + + /*** + * Gets the character(s) at a given index. + * @param index Indicies of the character(s) requested. + * @param loop Loop around the string or stop at the end, default = true. + * @returns Character(s) at the specified indices. + * @extra When [loop] is true, overshooting the end of the string + * (or the beginning) will begin counting from the other end. + * As an alternate syntax, passing multiple indexes will get + * the characters at those indexes. + * @example + * 'jumpy'.at(0) -> 'j' + * 'jumpy'.at(2) -> 'm' + * 'jumpy'.at(5) -> 'j' + * 'jumpy'.at(5, false) -> '' + * 'jumpy'.at(-1) -> 'y' + * 'lucky charms'.at(2,4,6,8) -> ['u','k','y',c'] + ***/ + at(index: number, loop?: bool): string; + + /** + * @see at + * @limitation Typescript does not allow for arguments + * after a variable argument list. + **/ + at(...indicies: number[]): string[]; + + /** + * Converts underscores and hyphens to camel case. + * @param first If [first] is true the first letter will also be capitalized, default = true + * @returns Camel case version of the string. + * @extra If the Inflections package is included acryonyms can also + * be defined that will be used when camelizing. + * @example + * 'caps_lock'.camelize() -> 'CapsLock' + * 'moz-border-radius'.camelize() -> 'MozBorderRadius' + * 'moz-border-radius'.camelize(false) -> 'mozBorderRadius' + **/ + camelize(first?: bool): string; + + /** + * Capitalizes the first character in the string. + * @method capitalize([all] = false) + * @param all Default = false + * @returns String + * @extra If [all] is true, all words in the string will be capitalized. + * @example + * + * 'hello'.capitalize() -> 'Hello' + * 'hello kitty'.capitalize() -> 'Hello kitty' + * 'hello kitty'.capitalize(true) -> 'Hello Kitty' + * + **/ + capitalize(all: bool): string; + + /** + * Runs callback [fn] against each character in the string. + * Returns an array of characters. + * @param fn Callback function for each character in the string. + * @returns string[] with each element containing one character + * in the string. + * @example + * 'jumpy'.chars() -> ['j','u','m','p','y'] + * 'jumpy'.chars(function(c) { + * // Called 5 times: "j","u","m","p","y" + * }); + **/ + chars(fn?: (c: string) => void ): string[]; + + /** + * Runs callback [fn] against each character code in the string. + Returns an array of character codes. + * @param fn Callback function for each character code in the string. + * @returns number[] with each element containing one character code + * in the string. + * @example + * 'jumpy'.codes() -> [106,117,109,112,121] + * 'jumpy'.codes(function(c) { + * // Called 5 times: 106, 117, 109, 112, 121 + * }); + ***/ + codes(fn?: (c: string) => void ): number[]; + + /** + * Compacts all white space in the string to a single space and trims the ends. + * @returns String with all whitespace compated to a single space. + * @example + * 'too \n much \n space'.compact() -> 'too much space' + * 'enough \n '.compact() -> 'enough' + **/ + compact(): string; + + /** + * Converts underscores and camel casing to hypens. + * @returns String with underscores and camel casing changed to hypens. + * @example + * 'a_farewell_to_arms'.dasherize() -> 'a-farewell-to-arms' + * 'capsLock'.dasherize() -> 'caps-lock' + **/ + dasherize(): string; + + /** + * Decodes the string from base64 encoding. + * @returns Decoded base64 string. + * @extra This method wraps the browser native %atob% when available, + * and uses a custom implementation when not available. + * @example + * 'aHR0cDovL3R3aXR0ZXIuY29tLw=='.decodeBase64() -> 'http://twitter.com/' + * 'anVzdCBnb3QgZGVjb2RlZA=='.decodeBase64() -> 'just got decoded!' + **/ + decodeBase64(): string; + + /** + * Runs callback [fn] against each occurence of [search]. + * @param fn Callback function for each occurance of [search]. + * If [search] is not provided each character is matched. + * @param search Search item to look for in the string. + * @returns string[] of each item matched in the string. + * @extra Returns an array of matches. [search] may be either + * a string or regex, and defaults to every character in the string. + * @example + * 'jumpy'.each() -> ['j','u','m','p','y'] + * 'jumpy'.each(/[r-z]/) -> ['u','y'] + * 'jumpy'.each(/[r-z]/, function(m) { + * // Called twice: "u", "y" + * }); + **/ + each(search: string, fn?: (m: string) => void ): string[]; + + /** + * @see each + **/ + each(search: RegExp, fn?: (m: string) => void ): string[]; + + /** + * @see each + **/ + each(fn?: (m: string) => void ): string[]; + + /** + * Encodes the string into base64 encoding. + * @returns Base64 encoded string. + * @extra This method wraps the browser native %btoa% when available, + * and uses a custom implementation when not available. + * @example + * 'gonna get encoded!'.encodeBase64() -> 'Z29ubmEgZ2V0IGVuY29kZWQh' + * 'http://twitter.com/'.encodeBase64() -> 'aHR0cDovL3R3aXR0ZXIuY29tLw==' + **/ + encodeBase64(): string; + + /** + * Returns true if the string ends with . + * @param find String or RegExp to find at the end of the string. + * @param pos Ending position to search for, defaults to the end of the string. + * @param case_ True for case sensitive, default = true. + * @returns True if the string ends with . + * @example + * 'jumpy'.endsWith('py') -> true + * 'jumpy'.endsWith(/[q-z]/) -> true + * 'jumpy'.endsWith('MPY') -> false + * 'jumpy'.endsWith('MPY', false) -> true + **/ + endsWith(find: string, pos?: number, case_?: bool): bool; + + /** + * @see endsWith + **/ + endsWith(find: string, case_?: bool): bool; + + /** + * @see endsWith + **/ + endsWith(find: RegExp, pos?: number, case_?: bool): bool; + + /** + * @see endsWith + **/ + endsWith(find: RegExp, case_?: bool): bool; + + /** + * Converts HTML characters to their entity equivalents. + * @returns HTML escaped string. + * @example + * '

some text

'.escapeHTML() -> '<p>some text</p>' + * 'one & two'.escapeHTML() -> 'one & two' + **/ + escapeHTML(): string; + + /** + * Escapes all RegExp tokens in the string. + * @returns RegExp escaped string. + * @example + * 'really?'.escapeRegExp() -> 'really\?' + * 'yes.'.escapeRegExp() -> 'yes\.' + * '(not really)'.escapeRegExp() -> '\(not really\)' + **/ + escapeRegExp(): string; + + /** + * Escapes characters in a string to make a valid URL. + * @returns URL escaped string. + * @extra If [param] is true, it will also escape valid URL + * characters for use as a URL parameter. + * @example + * 'http://foo.com/"bar"'.escapeURL() -> 'http://foo.com/%22bar%22' + * 'http://foo.com/"bar"'.escapeURL(true) -> 'http%3A%2F%2Ffoo.com%2F%22bar%22' + **/ + escapeURL(param?: bool): string; + + /** + * Returns the first [n] characters of the string. + * @returns String + * @example + * 'lucky charms'.first() -> 'l' + * 'lucky charms'.first(3) -> 'luc' + **/ + first(n?: number): string; + + /** + * Returns a section of the string starting from [index]. + * @returns String + * @example + * 'lucky charms'.from() -> 'lucky charms' + * 'lucky charms'.from(7) -> 'harms' + **/ + from(index?: number): string; + + /** + * Converts full-width characters (zenkaku) to half-width (hankaku). + * @param mode default = 'all' + * @returns Converted string to hankaku. + * @extra [mode] accepts any combination of + * "a" (alphabet), + * "n" (numbers), + * "k" (katakana), + * "s" (spaces), + * "p" (punctuation), + * or "all". + * @example + * '??? YAMADA??!'.hankaku() -> '??? YAMADA??!' + * '??? YAMADA??!'.hankaku('a') -> '??? YAMADA??!' + * '??? YAMADA??!'.hankaku('alphabet') -> '??? YAMADA??!' + * '?????! 25???!'.hankaku('katakana', 'numbers') -> '?????! 25???!' + * '?????! 25???!'.hankaku('k', 'n') -> '?????! 25???!' + * '?????! 25???!'.hankaku('kn') -> '?????! 25???!' + * '?????! 25???!'.hankaku('sp') -> '?????! 25???!' + **/ + hankaku(mode?: string): string; + + /** + * @see hankaku + **/ + hankaku(...modes: string[]): string; + + /** + * Returns true if the string matches . + * @param find Search parameters. + * @returns True if the string matchs , otherwise false. + * @example + * 'jumpy'.has('py') -> true + * 'broken'.has(/[a-n]/) -> true + * 'broken'.has(/[s-z]/) -> false + **/ + has(find: string): bool; + + /** + * @see has + **/ + has(find: RegExp): bool; + + /** + * Returns true if the string contains any characters in Arabic. + * @returns True if the string contains Arabic. + * @example + * '?????'.hasArabic() -> true + * '?????'.hasCyrillic() -> true + * '? ?????!'.hasHangul() -> true + * '??????'.hasKatakana() -> true + * "l'année".hasLatin() -> true + **/ + hasArabic(): bool; + + /** + * Returns true if the string contains any characters in Cyrillic. + * @returns True if the string contains Cyrillic. + **/ + hasCyrillic(): bool; + + /** + * Returns true if the string contains any characters in Greek. + * @returns True if the string contains Greek. + **/ + hasGreek(): bool; + + /** + * Returns true if the string contains any characters in Hangul. + * @returns True if the string contains Hangul. + **/ + hasHangul(): bool; + + /** + * Returns true if the string contains any characters in Han. + * @returns True if the string contains Han. + **/ + hasHan(): bool; + + /** + * Returns true if the string contains any characters in Kanji. + * @returns True if the string contains Kanji. + **/ + hasKanji(): bool; + + /** + * Returns true if the string contains any characters in Hebrew. + * @returns True if the string contains Hebrew. + **/ + hasHebrew(): bool; + + /** + * Returns true if the string contains any characters in Hiragana. + * @returns True if the string contains Hiragana. + **/ + hasHiragana(): bool; + + /** + * Returns true if the string contains any characters in Kana. + * @returns True if the string contains Kana. + **/ + hasKana(): bool; + + /** + * Returns true if the string contains any characters in Katakana. + * @returns True if the string contains Katakana. + **/ + hasKatakana(): bool; + + /** + * Returns true if the string contains any characters in Latin. + * @returns True if the string contains Latin. + **/ + hasLatin(): bool; + + /** + * Returns true if the string contains any characters in Thai. + * @returns True if the string contains Thai. + **/ + hasThai(): bool; + + /** + * Returns true if the string contains any characters in Devanagari. + * @returns True if the string contains Devanagari. + **/ + hasDevanagari(): bool; + + /** + * Converts katakana into hiragana. + * @param all If [all] is false, only full-width katakana will be converted, default = true. + * @returns Converted string to hiragana. + * @example + * '????'.hiragana() -> '????' + * '?????'.hiragana() -> '?????' + * '????'.hiragana() -> '????' + * '????'.hiragana(false) -> '????' + **/ + hiragana(all?: bool): string; + + /** + * Creates a human readable string. + * @returns Pretty printed version of the string. + * @extra Capitalizes the first word and turns underscores into spaces and strips a + * trailing '_id', if any. Like String#titleize, this is meant for creating pretty output. + * @example + * 'employee_salary'.humanize() -> 'Employee salary' + * 'author_id'.humanize() -> 'Author' + **/ + humanize(): string; + + /** + * Returns true if the string has a length of 0 or contains only whitespace. + * @returns True if the string has a length of 0 or contains only whitespace. + * @example + * ''.isBlank() -> true + * ' '.isBlank() -> true + * 'noway'.isBlank() -> false + **/ + isBlank(): bool; + + /** + * Returns true if the string contains only characters in Arabic. Whitespace is ignored. + * @returns True if the string containsly only characters in Arabic. + * @example + * '?????'.isArabic() -> true + * '?????'.isCyrillic() -> true + * '? ?????!'.isHangul() -> true + * '??????'.isKatakana() -> false + * "l'année".isLatin() -> true + **/ + isArabic(): bool; + + /** + * Returns true if the string contains only characters in Cyrillic. Whitespace is ignored. + * @returns True if the string containsly only characters in Cyrillic. + **/ + isCyrillic(): bool; + + /** + * Returns true if the string contains only characters in Greek. Whitespace is ignored. + * @returns True if the string containsly only characters in Greek. + **/ + isGreek(): bool; + + /** + * Returns true if the string contains only characters in Hangul. Whitespace is ignored. + * @returns True if the string containsly only characters in Hangul. + **/ + isHangul(): bool; + + /** + * Returns true if the string contains only characters in Han. Whitespace is ignored. + * @returns True if the string containsly only characters in Han. + **/ + isHan(): bool; + + /** + * Returns true if the string contains only characters in Kanji. Whitespace is ignored. + * @returns True if the string containsly only characters in Kanji. + **/ + isKanji(): bool; + + /** + * Returns true if the string contains only characters in Hebrew. Whitespace is ignored. + * @returns True if the string containsly only characters in Hebrew. + **/ + isHebrew(): bool; + + /** + * Returns true if the string contains only characters in Hiragana. Whitespace is ignored. + * @returns True if the string containsly only characters in Hiragana. + **/ + isHiragana(): bool; + + /** + * Returns true if the string contains only characters in Kana. Whitespace is ignored. + * @returns True if the string containsly only characters in Kana. + **/ + isKana(): bool; + + /** + * Returns true if the string contains only characters in Katakana. Whitespace is ignored. + * @returns True if the string containsly only characters in Katakana. + **/ + isKatakana(): bool; + + /** + * Returns true if the string contains only characters in Latin. Whitespace is ignored. + * @returns True if the string containsly only characters in Latin. + **/ + isLatin(): bool; + + /** + * Returns true if the string contains only characters in Thai. Whitespace is ignored. + * @returns True if the string containsly only characters in Thai. + **/ + isThai(): bool; + + /** + * Returns true if the string contains only characters in Devanagari. Whitespace is ignored. + * @returns True if the string containsly only characters in Devanagari. + **/ + isDevanagari(): bool; + + /** + * Converts hiragana into katakana. + * @returns Converted string to katakana. + * @example + * '????'.katakana() -> '????' + * '?????'.katakana() -> '?????' + **/ + katakana(): string; + + /** + * Returns the last [n] characters of the string. + * @param last Default = 1. + * @returns The last [n] characters of the string. + * @example + * 'lucky charms'.last() -> 's' + * 'lucky charms'.last(3) -> 'rms' + **/ + last(n?: number): string; + + /** + * Runs callback [fn] against each line in the string. + * @param fn Callback against each line in the original string. + * @returns A string[] where each element is a line in the original string. + * @example + * 'broken wear\nand\njumpy jump'.lines() -> ['broken wear','and','jumpy jump'] + * 'broken wear\nand\njumpy jump'.lines(function(l) { + * // Called three times: "broken wear", "and", "jumpy jump" + * }); + **/ + lines(fn?: (l: string) => void): string[]; + + /** + * Returns the string with accented and non-standard Latin-based + * characters converted into ASCII approximate equivalents. + * @returns String + * @example + * 'á'.normalize() -> 'a' + * 'Ménage à trois'.normalize() -> 'Menage a trois' + * 'Volkswagen'.normalize() -> 'Volkswagen' + * 'FULLWIDTH'.normalize() -> 'FULLWIDTH' + **/ + normalize(): string; + + /** + * Pads either/both sides of the string. + * @param padding The padding characters to add to the string. + * @param num The number of to add to the string, default = 1. + * @returns String + * @extra [num] is the number of characters on each side, + * and [padding] is the character to pad with. + * @example + * 'wasabi'.pad('-') -> '-wasabi-' + * 'wasabi'.pad('-', 2) -> '--wasabi--' + * 'wasabi'.padLeft('-', 2) -> '--wasabi' + * 'wasabi'.padRight('-', 2) -> 'wasabi--' + **/ + pad(padding: string, num?: number): string; + + /** + * @see pad + **/ + padLeft(padding: string, num?: number): string; + + /** + * @see pad + **/ + padRight(padding: string, num?: number): string; + + /** + * Runs callback [fn] against each paragraph in the string. + * @param fn Callback function called for each paragraph in the string. + * @returns Returns a string[] where each element is a paragraph in the original string. + * @extra A paragraph here is defined as a block of text bounded + * by two or more line breaks. + * @example + * 'Once upon a time.\n\nIn the land of oz...'.paragraphs() -> ['Once upon a time.','In the land of oz...'] + * 'Once upon a time.\n\nIn the land of oz...'.paragraphs(function(p) { + * // Called twice: "Once upon a time.", "In teh land of oz..." + * }); + **/ + paragraphs(fn?: (p: string) => void): string[]; + + /** + * Replaces special characters in a string so that it may be used as part of a pretty URL. + * @returns URL parameterizes the string. + * @example + * 'hell, no!'.parameterize() -> 'hell-no' + **/ + parameterize(): string; + + /** + * Returns the plural form of the word in the string. + * @method pluralize() + * @returns String + * @example + * 'post'.pluralize() -> 'posts' + * 'octopus'.pluralize() -> 'octopi' + * 'sheep'.pluralize() -> 'sheep' + * 'words'.pluralize() -> 'words' + * 'CamelOctopus'.pluralize() -> 'CamelOctopi' + **/ + pluralize(): string; + + /** + * Removes any part of the string that matches . + * @param find Remove this from the string. + * @returns String with all instances of removed. + * @extra can be a string or a regex. + * @example + * 'schfifty five'.remove('f') -> 'schity ive' + * 'schfifty five'.remove(/[a-f]/g) -> 'shity iv' + **/ + remove(find: string): string; + + /** + * @see remove + **/ + remove(find: RegExp): string; + + /** + * Removes all HTML tags and their contents from the string + * @returns String with HTML tags removed. + * @extra Tags to remove may be enumerated in the parameters, otherwise will remove all. + * @example + * '

just some text

'.removeTags() -> '' + * '

just some text

'.removeTags('b') -> '

just text

' + **/ + removeTags(): string; + + /** + * @see removeTags + * @param tag Remove only this HTML tag. + **/ + removeTags(tag: string): string; + + /** + * @see removeTags + * @param tags Remove these HTML tags. + **/ + removeTags(...tags: string[]): string; + + /** + * Returns the string repeated [num] times. + * @param num Number of times to repeat the string, default = 0. + * @returns Repeated [num] string. + * @example + * 'jumpy'.repeat(2) -> 'jumpyjumpy' + * 'a'.repeat(5) -> 'aaaaa' + * 'a'.repeat(0) -> '' + **/ + repeat(num?: number): string; + + /** + * Reverses the string. + * @returns Reversed string. + * @example + * 'jumpy'.reverse() -> 'ypmuj' + * 'lucky charms'.reverse() -> 'smrahc ykcul' + **/ + reverse(): string; + + /** + * Shifts each character in the string places in the character map. + * @param num Number of characters to shift in the character map. + * @returns String with characters shifted . + * @example + * 'a'.shift(1) -> 'b' + * '?'.shift(1) -> '?' + **/ + shift(num: number): string[]; + + /** + * The reverse of String#pluralize. + * @returns Returns the singular form of a word in a string. + * @example + * 'posts'.singularize() -> 'post' + * 'octopi'.singularize() -> 'octopus' + * 'sheep'.singularize() -> 'sheep' + * 'word'.singularize() -> 'word' + * 'CamelOctopi'.singularize() -> 'CamelOctopus' + **/ + singularize(): string; + + /** + * Converts camel case, underscores, and hyphens to a properly spaced string. + * @returns String + * @example + * 'camelCase'.spacify() -> 'camel case' + * 'an-ugly-string'.spacify() -> 'an ugly string' + * 'oh-no_youDid-not'.spacify().capitalize(true) -> 'something else' + **/ + spacify(): string; + + /** + * Returns true if the string starts with . + * @param find String or RegExp to look for at the beginning of the string. + * @param pos Starting position to start searching, default = 0. + * @param case_ True for case sensitive, default = true. + * @returns True if the string starts with `find`. + * @example + * 'hello'.startsWith('hell') -> true + * 'hello'.startsWith(/[a-h]/) -> true + * 'hello'.startsWith('HELL') -> false + * 'hello'.startsWith('HELL', false) -> true + **/ + startsWith(find: string, pos?: number, case_?: bool): bool; + + /** + * @see startsWith + **/ + startsWith(find: string, case_?: bool): bool; + + /** + * @see startsWith + **/ + startsWith(find: RegExp, pos?: number, case_?: bool): bool; + + /** + * @see startsWith + **/ + startsWith(find: RegExp, case_?: bool): bool; + + /*** + * Strips all HTML tags from the string. + * @method stripTags([tag1], [tag2], ...) + * @returns String + * @extra Tags to strip may be enumerated in the parameters, + * otherwise will strip all. + * @example + * + * '

just some text

'.stripTags() -> 'just some text' + * '

just some text

'.stripTags('p') -> 'just some text' + * + ***/ + stripTags(): string; + stripTags(tag: string): string; + stripTags(...tags: string[]): string; + + /*** + * Creates a title version of the string. + * @method titleize() + * @returns String + * @extra Capitalizes all the words and replaces some characters + * in the string to create a nicer looking title. + * String#titleize is meant for creating pretty output. + * @example + * + * 'man from the boondocks'.titleize() -> 'Man from the Boondocks' + * 'x-men: the last stand'.titleize() -> 'X Men: The Last Stand' + * 'TheManWithoutAPast'.titleize() -> 'The Man Without a Past' + * 'raiders_of_the_lost_ark'.titleize() -> 'Raiders of the Lost Ark' + * + ***/ + titleize(): string; + + /*** + * Returns a section of the string ending at [index]. + * @method to([index] = end) + * @returns String + * @example + * + * 'lucky charms'.to() -> 'lucky charms' + * 'lucky charms'.to(7) -> 'lucky ch' + * + ***/ + to(index?: number): string; + + /*** + * Converts the string into a number. + * @method toNumber([base] = 10) + * @returns Number + * @extra Any value with a "." fill be converted to a floating point value, + * otherwise an integer. + * @example + * + * '153'.toNumber() -> 153 + * '12,000'.toNumber() -> 12000 + * '10px'.toNumber() -> 10 + * 'ff'.toNumber(16) -> 255 + * + ***/ + toNumber(base?: number): number; + + /*** + * Removes leading and/or trailing whitespace from the string. + * @method trim[Side]() + * @returns String + * @extra Whitespace is defined as line breaks, tabs, and any character + * in the "Space, Separator" Unicode category, conforming to the + * the ES5 spec. The standard %trim% method is only added when + * not fully supported natively. + * + * @set + * trim + * trimLeft + * trimRight + * + * @example + * + * ' wasabi '.trim() -> 'wasabi' + * ' wasabi '.trimLeft() -> 'wasabi ' + * ' wasabi '.trimRight() -> ' wasabi' + * + ***/ + trim(): string; + trimLeft(): string; + trimRight(): string; + + /*** + * Truncates a string. + * @method truncate(, [split] = true, [from] = 'right', [ellipsis] = '...') + * @returns Object + * @extra If [split] is %false%, will not split words up, and instead + * discard the word where the truncation occurred. [from] can + * also be %"middle"% or %"left"%. + * @example + * + * 'just sittin on the dock of the bay'.truncate(20) -> 'just sittin on the do...' + * 'just sittin on the dock of the bay'.truncate(20, false) -> 'just sittin on the...' + * 'just sittin on the dock of the bay'.truncate(20, true, 'middle') -> 'just sitt...of the bay' + * 'just sittin on the dock of the bay'.truncate(20, true, 'left') -> '...the dock of the bay' + * + ***/ + truncate(length: number, split?: bool, from?: string, ellipsis?: string): string; + + /*** + * Converts hyphens and camel casing to underscores. + * @method underscore() + * @returns String + * @example + * + * 'a-farewell-to-arms'.underscore() -> 'a_farewell_to_arms' + * 'capsLock'.underscore() -> 'caps_lock' + * + ***/ + underscore(): string; + + /*** + * Restores escaped HTML characters. + * @method unescapeHTML([partial] = false) + * @returns String + * @example + * + * '<p>some text</p>'.unescapeHTML() -> '

some text

' + * 'one & two'.unescapeHTML() -> 'one & two' + * + ***/ + unescapeHTML(partial?: bool): string; + + /*** + * Restores escaped characters in a URL escaped string. + * @method unescapeURL([partial] = false) + * @returns String + * @extra If [partial] is true, it will only unescape non-valid URL characters. [partial] is included here for completeness, but should very rarely be needed. + * @example + * + * 'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL() -> 'http://foo.com/the bar' + * 'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL(true) -> 'http%3A%2F%2Ffoo.com%2Fthe bar' + * + ***/ + unescapeURL(partial?: bool): string; + + /*** + * Runs callback [fn] against each word in the string. + * Returns an array of words. + * @method words([fn]) + * @returns String[] + * @extra A "word" here is defined as any sequence of non-whitespace characters. + * @example + * + * 'broken wear'.words() -> ['broken','wear'] + * 'broken wear'.words(function(w) { + * // Called twice: "broken", "wear" + * }); + * + ***/ + words(fn?: Function): string[]; + + /*** + * Converts half-width characters (hankaku) to full-width (zenkaku). + * @method zenkaku([mode] = 'all') + * @returns String + * @extra [mode] accepts any combination of + * "a" (alphabet), + * "n" (numbers), + * "k" (katakana), + * "s" (spaces), + * "p" (punctuation), + * or "all". + * @example + * + * '??? YAMADA??!'.zenkaku() -> '??? YAMADA??!' + * '??? YAMADA??!'.zenkaku('a') -> '??? YAMADA??!' + * '??? YAMADA??!'.zenkaku('alphabet') -> '??? YAMADA??!' + * '?????! 25???!'.zenkaku('katakana', 'numbers') -> '?????! 25???!' + * '?????! 25???!'.zenkaku('k', 'n') -> '?????! 25???!' + * '?????! 25???!'.zenkaku('kn') -> '?????! 25???!' + * '?????! 25???!'.zenkaku('sp') -> '?????! 25???!' + * + ***/ + zenkaku(mode?: string): string; +} + +interface Number { + + /*** + * Returns a random integer between [n1] and [n2]. + * @method Number.random([n1], [n2]) + * @returns Number + * @extra If only 1 number is passed, the other will be 0. If none are passed, the number will be either 0 or 1. + * @example + * + * Number.random(50, 100) -> ex. 85 + * Number.random(50) -> ex. 27 + * Number.random() -> ex. 0 + * + ***/ + random(n1?: number, n2?: number): number; + + /*** + * Returns an abbreviated form of the number. + * @method abbr([precision] = 0) + * @returns String + * @extra [precision] will round to the given precision. + * @example + * + * (1000).abbr() -> "1k" + * (1000000).abbr() -> "1m" + * (1280).abbr(1) -> "1.3k" + * + ***/ + abbr(precision?: number): string; + + /*** + * Returns an abbreviated form of the number, considered to be "Bytes". + * @method bytes([precision] = 0, [limit] = 4) + * @returns String + * @extra [precision] will round to the given precision. + * [limit] is the upper limit for the units. + * The default is %4%, which is "terabytes" (TB). + * If [limit] is %false%, the upper limit will be "exa". + * @example + * + * (1000).bytes() -> "1kB" + * (1000).bytes(2) -> "0.98kB" + * ((10).pow(20)).bytes() -> "90,949,470TB" + * ((10).pow(20)).bytes(0, false) -> "87EB" + * + ***/ + bytes(precision?: number, limit?: number): string; + bytes(precision?: number, limit?: bool): string; + + /*** + * Shortcut for %Math.ceil% that also allows a . + * @method ceil( = 0) + * @returns Number + * + * @example + * + * (3.241).ceil() -> 4 + * (-3.241).ceil() -> -3 + * (3.241).ceil(2) -> 3.25 + * (3748).ceil(-2) -> 3800 + * + ***/ + ceil(precision?: number): number; + + /*** + * Returns a string at the code point of the number. + * @method chr() + * @returns String + * @example + * + * (65).chr() -> "A" + * (75).chr() -> "K" + * + ***/ + chr(): string; + + /*** + * Returns an array containing numbers from the number down to . + * @method downto(, [fn], [step] = 1) + * @returns Array + * @extra Optionally calls [fn] callback for each number in that array. + * [step] allows multiples greater than 1. + * @example + * + * (8).downto(3) -> [8, 7, 6, 5, 4, 3] + * (8).downto(3, function(n) { + * // This function is called 6 times receiving n as the value. + * }); + * (8).downto(2, null, 2) -> [8, 6, 4, 2] + * + ***/ + downto(num: number, fn?: Function, step?: number): number[]; + + /*** + * Takes the number as milliseconds and returns a unit- + * adjusted localized string. + * @method duration([locale] = currentLocale) + * @returns String + * @extra This method is the same as %Date#relative% without + * the localized equivalent of "from now" or "ago". + * [locale] can be passed as the first (and only) parameter. + * Note that this method is only available when the dates + * package is included. + * @example + * + * (500).duration() -> '500 milliseconds' + * (1200).duration() -> '1 second' + * (75).minutes().duration() -> '1 hour' + * (75).minutes().duration('es') -> '1 hora' + * + ***/ + duration(locale?: string): string; + + /*** + * Shortcut for %Math.floor% that also allows a . + * @method floor( = 0) + * @returns Number + * @example + * + * (3.241).floor() -> 3 + * (-3.841).floor() -> -4 + * (3.241).floor(2) -> 3.24 + * (3748).floor(-2) -> 3700 + * + ***/ + floor(precision?: number): number; + + /*** + * Formats the number to a readable string. + * @method format([place] = 0, [thousands] = ',', [decimal] = '.') + * @returns String + * @extra If [place] is %undefined%, will automatically determine the place. + * [thousands] is the character used for the thousands separator. + * [decimal] is the character used for the decimal point. + * @example + * + * (56782).format() -> '56,782' + * (56782).format(2) -> '56,782.00' + * (4388.43).format(2, ' ') -> '4 388.43' + * (4388.43).format(2, '.', ',') -> '4.388,43' + * + ***/ + format(place?: number, thousands?: string, decimal?: string): string; + + /*** + * Converts the number to hexidecimal. + * @method hex([pad] = 1) + * @returns String + * @extra [pad] will pad the resulting string to that many places. + * @example + * + * (255).hex() -> 'ff'; + * (255).hex(4) -> '00ff'; + * (23654).hex() -> '5c66'; + * + ***/ + hex(pad?: number): string; + + /*** + * Returns true if the number is even. + * @method isEven() + * @returns Boolean + * @example + * + * (6).isEven() -> true + * (17).isEven() -> false + * + ***/ + isEven(): bool; + + /*** + * Returns true if the number has no trailing decimal. + * @method isInteger() + * @returns Boolean + * @example + * + * (420).isInteger() -> true + * (4.5).isInteger() -> false + * + ***/ + isInteger(): bool; + + /*** + * Returns true if the number is a multiple of . + * @method isMultipleOf() + * @returns Boolean + * @example + * + * (6).isMultipleOf(2) -> true + * (17).isMultipleOf(2) -> false + * (32).isMultipleOf(4) -> true + * (34).isMultipleOf(4) -> false + * + ***/ + isMultipleOf(num: number): bool; + + /*** + * Returns true if the number is odd. + * @method isOdd() + * @returns Boolean + * @example + * + * (3).isOdd() -> true + * (18).isOdd() -> false + * + ***/ + isOdd(): bool; + + /*** + * Returns the logarithm of the number with base , + * or natural logarithm of the number if is undefined. + * @method log( = Math.E) + * @returns Number + * @example + * + * (64).log(2) -> 6 + * (9).log(3) -> 2 + * (5).log() -> 1.6094379124341003 + * + ***/ + log(base?: number): number; + + /*** + * Math related functions are mapped as shortcuts to numbers and are identical. Note that %Number#log% provides some special defaults. + * @method [math]() + * @returns Number + * + * @set + * abs + * sin + * asin + * cos + * acos + * tan + * atan + * sqrt + * exp + * pow + * + * @example + * + * (3).pow(3) -> 27 + * (-3).abs() -> 3 + * (1024).sqrt() -> 32 + * + ***/ + abs(): number; + sin(): number; + asin(): number; + cos(): number; + acos(): number; + tan(): number; + atan(): number; + sqrt(): number; + exp(): number; + pow(num: number): number; + + /*** + * Returns the number as a string in metric notation. + * @method metric([precision] = 0, [limit] = 1) + * @returns String + * @extra [precision] will round to the given precision. + * Both very large numbers and very small numbers are supported. + * [limit] is the upper limit for the units. + * The default is %1%, which is "kilo". + * If [limit] is %false%, the upper limit will be "exa". + * The lower limit is "nano", and cannot be changed. + * @example + * + * (1000).metric() -> "1k" + * (1000000).metric() -> "1,000k" + * (1000000).metric(0, false) -> "1M" + * (1249).metric(2) + 'g' -> "1.25kg" + * (0.025).metric() + 'm' -> "25mm" + * + ***/ + metric(precision?: number, limit?: number): string; + metric(precision?: number, limit?: bool): string; + + /*** + * Returns an ordinalized (English) string, i.e. "1st", "2nd", etc. + * @method ordinalize() + * @returns String + * @example + * + * (1).ordinalize() -> '1st'; + * (2).ordinalize() -> '2nd'; + * (8).ordinalize() -> '8th'; + * + ***/ + ordinalize(): string; + + /*** + * Pads a number with "0" to . + * @method pad( = 0, [sign] = false, [base] = 10) + * @returns String + * @extra [sign] allows you to force the sign as well (+05, etc). [base] can change the base for numeral conversion. + * @example + * + * (5).pad(2) -> '05' + * (-5).pad(4) -> '-0005' + * (82).pad(3, true) -> '+082' + * + ***/ + pad(place?: number, sign?: bool, base?: number): string; + + /*** + * Shortcut for %Math.round% that also allows a . + * @method round( = 0) + * @returns Number + * + * @example + * + * (3.241).round() -> 3 + * (-3.841).round() -> -4 + * (3.241).round(2) -> 3.24 + * (3748).round(-2) -> 3800 + * + ***/ + round(precision?: number): number; + + /*** + * Calls a number of times equivalent to the number. + * @method times() + * @returns Number + * @example + * + * (8).times(function(i) { + * // This function is called 8 times. + * }); + * + ***/ + times(fn: Function): number; + + /*** + * Returns a number. This is mostly for compatibility reasons. + * @method toNumber() + * @returns Number + * @example + * + * (420).toNumber() -> 420 + * + ***/ + toNumber(): number; + + /*** + * Takes the number as a corresponding unit of time and + * converts to milliseconds. + * @method [unit]() + * @returns Number + * @extra Method names can be both singular and plural. + * Note that as "a month" is ambiguous as a unit of time, + * %months% will be equivalent to 30.4375 days, the average + * number in a month. Be careful using %months% if you need + * exact precision. + * + * @set + * millisecond + * milliseconds + * second + * seconds + * minute + * minutes + * hour + * hours + * day + * days + * week + * weeks + * month + * months + * year + * years + * + * @example + * + * (5).milliseconds() -> 5 + * (10).hours() -> 36000000 + * (1).day() -> 86400000 + * + ***/ + millisecond(): number; + milliseconds(): number; + second(): number; + seconds(): number; + minute(): number; + minutes(): number; + hour(): number; + hours(): number; + day(): number; + days(): number; + week(): number; + weeks(): number; + month(): number; + months(): number; + year(): number; + years(): number; + + /*** + * Returns a date units after [d], where is the number. + * @method [unit]After([d], [locale] = currentLocale) + * @returns Date + * @extra [d] will accept a date object, timestamp, or text format. + * Note that "months" is ambiguous as a unit of time. If the + * target date falls on a day that does not exist + * (ie. August 31 -> February 31), the date will be shifted + * to the last day of the month. Be careful using %monthsAfter% + * if you need exact precision. See @date_format for more. + * + * @set + * millisecondAfter + * millisecondsAfter + * secondAfter + * secondsAfter + * minuteAfter + * minutesAfter + * hourAfter + * hoursAfter + * dayAfter + * daysAfter + * weekAfter + * weeksAfter + * monthAfter + * monthsAfter + * yearAfter + * yearsAfter + * + * @example + * + * (5).daysAfter('tuesday') -> 5 days after tuesday of this week + * (1).yearAfter('January 23, 1997') -> January 23, 1998 + * + ***/ + millisecondAfter(d: string, locale?: string): Date; + millisecondAfter(d: Date, locale?: string): Date; + millisecondsAfter(d: string, locale?: string): Date; + millisecondsAfter(d: Date, locale?: string): Date; + secondAfter(d: string, locale?: string): Date; + secondAfter(d: Date, locale?: string): Date; + secondsAfter(d: string, locale?: string): Date; + secondsAfter(d: Date, locale?: string): Date; + minuteAfter(d: string, locale?: string): Date; + minuteAfter(d: Date, locale?: string): Date; + minutesAfter(d: string, locale?: string): Date; + minutesAfter(d: Date, locale?: string): Date; + hourAfter(d: string, locale?: string): Date; + hourAfter(d: Date, locale?: string): Date; + hoursAfter(d: string, locale?: string): Date; + hoursAfter(d: Date, locale?: string): Date; + dayAfter(d: string, locale?: string): Date; + dayAfter(d: Date, locale?: string): Date; + daysAfter(d: string, locale?: string): Date; + daysAfter(d: Date, locale?: string): Date; + weekAfter(d: string, locale?: string): Date; + weekAfter(d: Date, locale?: string): Date; + weeksAfter(d: string, locale?: string): Date; + weeksAfter(d: Date, locale?: string): Date; + monthAfter(d: string, locale?: string): Date; + monthAfter(d: Date, locale?: string): Date; + monthsAfter(d: string, locale?: string): Date; + yearAfter(d: string, locale?: string): Date; + yearAfter(d: Date, locale?: string): Date; + yearsAfter(d: string, locale?: string): Date; + yearsAfter(d: Date, locale?: string): Date; + + /*** + * Returns a date that is units ago. + * @method [unit]Ago() + * @returns Date + * @extra Note that "months" is ambiguous as a unit of time. + * If the target date falls on a day that does not exist + * (ie. August 31 -> February 31), the date will be shifted + * to the last day of the month. Be careful using %monthsAgo% + * if you need exact precision. + * + * @set + * millisecondAgo + * millisecondsAgo + * secondAgo + * secondsAgo + * minuteAgo + * minutesAgo + * hourAgo + * hoursAgo + * dayAgo + * daysAgo + * weekAgo + * weeksAgo + * monthAgo + * monthsAgo + * yearAgo + * yearsAgo + * + * @example + * + * (5).weeksAgo() -> 5 weeks ago + * (1).yearAgo() -> January 23, 1996 + * + ***/ + millisecondAgo(): Date; + millisecondsAgo(): Date; + secondAgo(): Date; + secondsAgo(): Date; + minuteAgo(): Date; + minutesAgo(): Date; + hourAgo(): Date; + hoursAgo(): Date; + dayAgo(): Date; + daysAgo(): Date; + weekAgo(): Date; + weeksAgo(): Date; + monthAgo(): Date; + monthsAgo(): Date; + yearAgo(): Date; + yearsAgo(): Date; + + /*** + * Returns a date that is units before [d], where is the number. + * @method [unit]Before([d], [locale] = currentLocale) + * @returns Date + * @extra [d] will accept a date object, timestamp, or text format. + * Note that "months" is ambiguous as a unit of time. If the + * target date falls on a day that does not exist + * (ie. August 31 -> February 31), the date will be shifted to + * the last day of the month. Be careful using %monthsBefore% + * if you need exact precision. See @date_format for more. + * + * @set + * millisecondBefore + * millisecondsBefore + * secondBefore + * secondsBefore + * minuteBefore + * minutesBefore + * hourBefore + * hoursBefore + * dayBefore + * daysBefore + * weekBefore + * weeksBefore + * monthBefore + * monthsBefore + * yearBefore + * yearsBefore + * + * @example + * + * (5).daysBefore('tuesday') -> 5 days before tuesday of this week + * (1).yearBefore('January 23, 1997') -> January 23, 1996 + * + ***/ + millisecondBefore(d: string, locale?: string): Date; + millisecondBefore(d: Date, locale?: string): Date; + millisecondsBefore(d: string, locale?: string): Date; + millisecondsBefore(d: Date, locale?: string): Date; + secondBefore(d: string, locale?: string): Date; + secondBefore(d: Date, locale?: string): Date; + secondsBefore(d: string, locale?: string): Date; + secondsBefore(d: Date, locale?: string): Date; + minuteBefore(d: string, locale?: string): Date; + minuteBefore(d: Date, locale?: string): Date; + minutesBefore(d: string, locale?: string): Date; + minutesBefore(d: Date, locale?: string): Date; + hourBefore(d: string, locale?: string): Date; + hourBefore(d: Date, locale?: string): Date; + hoursBefore(d: string, locale?: string): Date; + hoursBefore(d: Date, locale?: string): Date; + dayBefore(d: string, locale?: string): Date; + dayBefore(d: Date, locale?: string): Date; + daysBefore(d: string, locale?: string): Date; + daysBefore(d: Date, locale?: string): Date; + weekBefore(d: string, locale?: string): Date; + weekBefore(d: Date, locale?: string): Date; + weeksBefore(d: string, locale?: string): Date; + weeksBefore(d: Date, locale?: string): Date; + monthBefore(d: string, locale?: string): Date; + monthBefore(d: Date, locale?: string): Date; + monthsBefore(d: string, locale?: string): Date; + monthsBefore(d: Date, locale?: string): Date; + yearBefore(d: string, locale?: string): Date; + yearBefore(d: Date, locale?: string): Date; + yearsBefore(d: string, locale?: string): Date; + yearsBefore(d: Date, locale?: string): Date; + + /*** + * Returns a date units from now. + * @method [unit]FromNow() + * @returns Date + * @extra Note that "months" is ambiguous as a unit of time. + * If the target date falls on a day that does not exist + * (ie. August 31 -> February 31), the date will be shifted + * to the last day of the month. Be careful using %monthsFromNow% + * if you need exact precision. + * + * @set + * millisecondFromNow + * millisecondsFromNow + * secondFromNow + * secondsFromNow + * minuteFromNow + * minutesFromNow + * hourFromNow + * hoursFromNow + * dayFromNow + * daysFromNow + * weekFromNow + * weeksFromNow + * monthFromNow + * monthsFromNow + * yearFromNow + * yearsFromNow + * + * @example + * + * (5).weeksFromNow() -> 5 weeks ago + * (1).yearFromNow() -> January 23, 1998 + * + ***/ + millisecondFromNow(): Date; + millisecondsFromNow(): Date; + secondFromNow(): Date; + secondsFromNow(): Date; + minuteFromNow(): Date; + minutesFromNow(): Date; + hourFromNow(): Date; + hoursFromNow(): Date; + dayFromNow(): Date; + daysFromNow(): Date; + weekFromNow(): Date; + weeksFromNow(): Date; + monthFromNow(): Date; + monthsFromNow(): Date; + yearFromNow(): Date; + yearsFromNow(): Date; + + /*** + * Returns an array containing numbers from the number up to . + * @method upto(, [fn], [step] = 1) + * @returns Array + * @extra Optionally calls [fn] callback for each number in that array. + * [step] allows multiples greater than 1. + * @example + * + * (2).upto(6) -> [2, 3, 4, 5, 6] + * (2).upto(6, function(n) { + * // This function is called 5 times receiving n as the value. + * }); + * (2).upto(8, null, 2) -> [2, 4, 6, 8] + * + ***/ + upto(num: number, fn?: Function, step?: number): number[]; +} + +interface Array { + + /*** + * Alternate array constructor. + * @method Array.create(, , ...) + * @returns Array + * @extra This method will create a single array by calling %concat% + * on all arguments passed. In addition to ensuring that an unknown + * variable is in a single, flat array (the standard constructor will + * create nested arrays, this one will not), it is also a useful + * shorthand to convert a function's arguments object into a standard + * array. + * @example + * + * Array.create('one', true, 3) -> ['one', true, 3] + * Array.create(['one', true, 3]) -> ['one', true, 3] + + Array.create(function(n) { + * return arguments; + * }('howdy', 'doody')); + * + ***/ + create(...args: any[]): any[]; + + /*** + * Returns true if is an Array. + * @method Array.isArray() + * @returns Boolean + * @extra This method is provided for browsers that don't support it internally. + * @example + * + * Array.isArray(3) -> false + * Array.isArray(true) -> false + * Array.isArray('wasabi') -> false + * Array.isArray([1,2,3]) -> true + * + ***/ + isArray(obj: any): bool; + + /*** + * Adds to the array. + * @method add(, [index]) + * @returns Array + * @extra If [index] is specified, it will add at [index], otherwise + * adds to the end of the array. %add% behaves like %concat% + * in that if is an array it will be joined, not inserted. + * This method will change the array! Use %include% for a + * non-destructive alias. Also, %insert% is provided as an + * alias that reads better when using an index. + * @example + * + * [1,2,3,4].add(5) -> [1,2,3,4,5] + * [1,2,3,4].add([5,6,7]) -> [1,2,3,4,5,6,7] + * [1,2,3,4].insert(8, 1) -> [1,8,2,3,4] + * + ***/ + add(el: any, index?: number): any[]; + add(el: any[], index?: number): any[]; + insert(el: any, index?: number): any[]; + insert(el: any[], index?: number): any[]; + + /*** + * Gets the element(s) at a given index. + * @method at(, [loop] = true) + * @returns Mixed + * @extra When [loop] is true, overshooting the end of the array (or the beginning) will begin counting from the other end. As an alternate syntax, passing multiple indexes will get the elements at those indexes. + * @example + * + * [1,2,3].at(0) -> 1 + * [1,2,3].at(2) -> 3 + * [1,2,3].at(4) -> 2 + * [1,2,3].at(4, false) -> null + * [1,2,3].at(-1) -> 3 + * [1,2,3].at(0,1) -> [1,2] + * + ***/ + at(index: number, loop?: bool): any; + at(start: number, stop: number): any[]; + + /*** + * Averages all values in the array. + * @method average([map]) + * @returns Number + * @extra [map] may be a function mapping the value to be averaged or + * a string acting as a shortcut. + * @example + * + * [1,2,3].average() -> 2 + + [{age:35},{age:11},{age:11}].average(function(n) { + * return n.age; + * }); -> 19 + * [{age:35},{age:11},{age:11}].average('age') -> 19 + * + ***/ + average(map?: (n: number) => number): number; + + /*** + * Clones the array. + * @method clone() + * @returns Array + * @example + * + * [1,2,3].clone() -> [1,2,3] + * + ***/ + clone(): any[]; + + /*** + * Removes all instances of %undefined%, %null%, and %NaN% from the array. + * @method compact([all] = false) + * @returns Array + * @extra If [all] is %true%, all "falsy" elements will be removed. This includes empty strings, 0, and false. + * @example + * + * [1,null,2,undefined,3].compact() -> [1,2,3] + * [1,'',2,false,3].compact() -> [1,'',2,false,3] + * [1,'',2,false,3].compact(true) -> [1,2,3] + * + ***/ + compact(all?: bool): any[]; + + /*** + * Counts all elements in the array that match . + * @method count() + * @returns Number + * @extra will match a string, number, array, object, or alternately test against a function or regex. This method implements @array_matching. + * @example + * + * [1,2,3,1].count(1) -> 2 + * ['a','b','c'].count(/b/) -> 1 + + [{a:1},{b:2}].count(function(n) { + * return n['a'] > 1; + * }); -> 0 + * + ***/ + count(f: number): number; + count(f: string): number; + count(f: any[]): number; + count(f: Object): number; + count(f: (n: any) => any): number; + count(f: RegExp): number; + + /*** + * Runs against each element in the array. Enhanced version of %Array#forEach%. + * @method each(, [index] = 0, [loop] = false) + * @returns Array + * @extra Parameters passed to are identical to %forEach%, + * ie. the first parameter is the current element, second + * parameter is the current index, and third parameter is + * the array itself. If returns %false% at any time + * it will break out of the loop. Once %each% finishes, + * it will return the array. If [index] is passed, will + * begin at that index and work its way to the end. If [loop] + * is true, it will then start over from the beginning of the + * array and continue until it reaches [index] - 1. + * @example + * + * [1,2,3,4].each(function(n) { + * // Called 4 times: 1, 2, 3, 4 + * }); + * [1,2,3,4].each(function(n) { + * // Called 4 times: 3, 4, 1, 2 + * }, 2, true); + * + ***/ + each(fn: (el: any, i?: number, array?: any[]) => bool, + index?: number, + loop?: bool): any[]; + + /*** + * Returns true if all elements in the array match . + * @method every(, [scope]) + * @returns Boolean + * @extra [scope] is the %this% object. %all% is provided an alias. + * In addition to providing this method for browsers that don't + * support it natively, this method also implements @array_matching. + * @example + * + + ['a','a','a'].every(function(n) { + * return n == 'a'; + * }); + * ['a','a','a'].every('a') -> true + * [{a:2},{a:2}].every({a:2}) -> true + ***/ + every(f: number, scope?: any): bool; + every(f: string, scope?: any): bool; + every(f: Object, scope?: any): bool; + every(f: (el: any, i?: number, array?: any[]) => bool, scope?: any): bool; + all(f: number, scope?: any): bool; + all(f: string, scope?: any): bool; + all(f: Object, scope?: any): bool; + all(f: (el: any, i?: number, array?: any[]) => bool, scope?: any): bool; + + /*** + * Removes any element in the array that matches [f1], [f2], etc. + * @method exclude([f1], [f2], ...) + * @returns Array + * @extra This is a non-destructive alias for %remove%. It will not change the original array. This method implements @array_matching. + * @example + * + * [1,2,3].exclude(3) -> [1,2] + * ['a','b','c'].exclude(/b/) -> ['a','c'] + * [{a:1},{b:2}].exclude(function(n) { + * return n['a'] == 1; + * }); -> [{b:2}] + * + ***/ + exclude(...f: number[]): number[]; + exclude(...f: string[]): string[]; + exclude(...f: RegExp[]): string[]; + exclude(...f: Object[]): Object[]; + exclude(...f: (el: any, i?: number, array?: any[]) => bool): any[]; + + /*** + * Returns any elements in the array that match . + * @method filter(, [scope]) + * @returns Array + * @extra [scope] is the %this% object. In addition to providing this + * method for browsers that don't support it natively, this method + * also implements @array_matching. + * @example + * + * [1,2,3].filter(function(n) { + * return n > 1; + * }); + * [1,2,2,4].filter(2) -> 2 + * + ***/ + filter(f: number, scope?: any): number[]; + filter(f: string, scope?: any): string[]; + filter(f: RegExp, scope?: any): String[]; + filter(f: Object, scope?: any): Object[]; + filter(f: (el: any, i?: number, array?: any[]) => bool, scope?: any): any[]; + + /*** + * Returns the first element that matches . + * @method find(, [index] = 0, [loop] = false) + * @returns Mixed + * @extra will match a string, number, array, object, or alternately + * test against a function or regex. Starts at [index], and will + * continue once from index = 0 if [loop] is true. This method + * implements @array_matching. + * @example + * + * [{a:1,b:2},{a:1,b:3},{a:1,b:4}].find(function(n) { + * return n['a'] == 1; + * }); -> {a:1,b:3} + * ['cuba','japan','canada'].find(/^c/, 2) -> 'canada' + * + ***/ + find(f: number, index?: number, loop?: bool): number; + find(f: string, index?: number, loop?: bool): string; + find(f: RegExp, index?: number, loop?: bool): string; + find(f: Object, index?: number, loop?: bool): Object; + find(f: (el: any, i?: number, array?: any[]) => bool, index?: number, loop?: bool): any; + + /*** + * Returns all elements that match . + * @method findAll(, [index] = 0, [loop] = false) + * @returns Array + * @extra will match a string, number, array, object, or alternately + * test against a function or regex. Starts at [index], and will + * continue once from index = 0 if [loop] is true. This method + * implements @array_matching. + * @example + * + * [{a:1,b:2},{a:1,b:3},{a:2,b:4}].findAll(function(n) { + * return n['a'] == 1; + * }); -> [{a:1,b:3},{a:1,b:4}] + * ['cuba','japan','canada'].findAll(/^c/) -> 'cuba','canada' + * ['cuba','japan','canada'].findAll(/^c/, 2) -> 'canada' + * + ***/ + findAll(f: number, index?: number, loop?: bool): number[]; + findAll(f: string, index?: number, loop?: bool): string[]; + findAll(f: RegExp, index?: number, loop?: bool): string[]; + findAll(f: Object, index?: number, loop?: bool): Object[]; + findAll(f: (el: any, i?: number, array?: any[]) => bool, index?: number, loop?: bool): any[]; + + /*** + * Returns the index of the first element that matches + * or -1 if not found. + * @method findIndex(, [startIndex] = 0, [loop] = false) + * @returns Number + * @extra This method has a few notable differences to native %indexOf%. + * Although will similarly match a primitive such as a string + * or number, it will also match deep objects and arrays that are + * not equal by reference (%===%). Additionally, if a function is + * passed it will be run as a matching function (similar to the + * behavior of %Array#filter%) rather than attempting to find that + * function itself by reference in the array. Starts at [index], + * and will continue once from index = 0 if [loop] is true. + * This method implements @array_matching. + * @example + * + * [1,2,3,4].findIndex(3); -> 2 + * [1,2,3,4].findIndex(function(n) { + * return n % 2 == 0; + * }); -> 1 + * ['one','two','three'].findIndex(/th/); -> 2 + * + ***/ + findIndex(f: number, startIndex?: number, loop?: bool): number; + findIndex(f: string, startIndex?: number, loop?: bool): number; + findIndex(f: RegExp, startIndex?: number, loop?: bool): number; + findIndex(f: Object, startIndex?: number, loop?: bool): number; + findIndex(f: RegExp, startIndex?: number, loop?: bool): number; + findIndex(f: (el: any, i?: number, array?: any[]) => bool, startIndex?: number, loop?: bool): number; + + /*** + * Returns the first element(s) in the array. + * @method first([num] = 1) + * @returns Mixed + * @extra When is passed, returns the first elements in the array. + * @example + * + * [1,2,3].first() -> 1 + * [1,2,3].first(2) -> [1,2] + * + ***/ + first(num?: number): any[]; + + /*** + * Returns a flattened, one-dimensional copy of the array. + * @method flatten([limit] = Infinity) + * @returns Array + * @extra You can optionally specify a [limit], which will only flatten + * that depth. + * @example + * + * [[1], 2, [3]].flatten() -> [1,2,3] + * [['a'],[],'b','c'].flatten() -> ['a','b','c'] + * + ***/ + flatten(limit?: number): any[]; + + /*** + * Iterates over the array, calling [fn] on each loop. + * @method forEach([fn], [scope]) + * @returns Nothing + * @extra This method is only provided for those browsers that do not support + * it natively. [scope] becomes the %this% object. + * @example + * + * ['a','b','c'].forEach(function(a) { + * // Called 3 times: 'a','b','c' + * }); + * + ***/ + forEach(fn: (el: any, i?: number, array?: any[]) => any, scope?: any): void; + + /*** + * Returns a slice of the array from . + * @method from() + * @returns Array + * @example + * + * [1,2,3].from(1) -> [2,3] + * [1,2,3].from(2) -> [3] + * + ***/ + from(index: number): any[]; + + /*** + * Groups the array by . + * @method groupBy(, [fn]) + * @returns Object + * @extra Will return an object with keys equal to the grouped values. + * may be a mapping function, or a string acting as a shortcut. + * Optionally calls [fn] for each group. + * @example + * + * ['fee','fi','fum'].groupBy('length') -> { 2: ['fi'], 3: ['fee','fum'] } + + [{age:35,name:'ken'},{age:15,name:'bob'}].groupBy(function(n) { + * return n.age; + * }); -> { 35: [{age:35,name:'ken'}], 15: [{age:15,name:'bob'}] } + * + ***/ + groupBy(map: string, fn?: (n: any) => void ): Object; + groupBy(fn: (n: any) => void ): Object; + + /*** + * Groups the array into arrays. + * @method inGroups(, [padding]) + * @returns Array + * @extra [padding] specifies a value with which to pad the last array + * so that they are all equal length. + * @example + * + * [1,2,3,4,5,6,7].inGroups(3) -> [ [1,2,3], [4,5,6], [7] ] + * [1,2,3,4,5,6,7].inGroups(3, 'none') -> [ [1,2,3], [4,5,6], [7,'none','none'] ] + * + ***/ + inGroups(num: number, padding?: any): any[][]; + + /*** + * Groups the array into arrays of elements each. + * @method inGroupsOf(, [padding] = null) + * @returns Array + * @extra [padding] specifies a value with which to pad the last array so that they are all equal length. + * @example + * + * [1,2,3,4,5,6,7].inGroupsOf(4) -> [ [1,2,3,4], [5,6,7] ] + * [1,2,3,4,5,6,7].inGroupsOf(4, 'none') -> [ [1,2,3,4], [5,6,7,'none'] ] + * + ***/ + inGroupsOf(num: number, padding?: any): any[][]; + + /*** + * Adds to the array. + * @method include(, [index]) + * @returns Array + * @extra This is a non-destructive alias for %add%. It will not change + * the original array. + * @example + * + * [1,2,3,4].include(5) -> [1,2,3,4,5] + * [1,2,3,4].include(8, 1) -> [1,8,2,3,4] + * [1,2,3,4].include([5,6,7]) -> [1,2,3,4,5,6,7] + * + ***/ + include(el: any, index?: number): any[]; + + /*** + * Searches the array and returns the first index where occurs, or -1 if the element is not found. + * @method indexOf(, [fromIndex]) + * @returns Number + * @extra [fromIndex] is the index from which to begin the search. + * This method performs a simple strict equality comparison on . + * It does not support enhanced functionality such as searching + * the contents against a regex, callback, or deep comparison of objects. + * For such functionality, use the %findIndex% method instead. + * @example + * + * [1,2,3].indexOf(3) -> 1 + * [1,2,3].indexOf(7) -> -1 + * + ***/ + indexOf(search: any, fromIndex?: number): number; + + /*** + * Returns an array containing the elements all arrays have in common. + * @method intersect([a1], [a2], ...) + * @returns Array + * @extra This method will also correctly operate on arrays of objects. + * @example + * + * [1,3,5].intersect([5,7,9]) -> [5] + * ['a','b'].intersect('b','c') -> ['b'] + * + ***/ + intersect(...args: number[]): number[]; + intersect(...args: string[]): string[]; + intersect(...args: Object[]): Object[]; + intersect(...args: any[]): any[]; + + /*** + * Returns true if the array is empty. + * @method isEmpty() + * @returns Boolean + * @extra This is true if the array has a length of zero, or contains + * only %undefined%, %null%, or %NaN%. + * @example + * + * [].isEmpty() -> true + * [null,undefined].isEmpty() -> true + * + ***/ + isEmpty(): bool; + + /*** + * Returns the last element(s) in the array. + * @method last([num] = 1) + * @returns Mixed + * @extra When is passed, returns the last elements in the array. + * @example + * + * [1,2,3].last() -> 3 + * [1,2,3].last(2) -> [2,3] + * + ***/ + last(): any; + last(num: number): any[]; + + /*** + * Searches the array and returns the last index where occurs, + * or -1 if the element is not found. + * @method lastIndexOf(, [fromIndex]) + * @returns Number + * @extra [fromIndex] is the index from which to begin the search. + * This method performs a simple strict equality comparison on . + * @example + * + * [1,2,1].lastIndexOf(1) -> 2 + * [1,2,1].lastIndexOf(7) -> -1 + * + ***/ + lastIndexOf(search: any, fromIndex?: number): number; + + /*** + * Returns the elements in the array with the least + * commonly occuring value. + * @method least([map]) + * @returns Array + * @extra [map] may be a function mapping the value to be checked or a + * string acting as a shortcut. + * @example + * + * [3,2,2].least() -> [3] + * ['fe','fo','fum'].least('length') -> ['fum'] + * [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].least(function(n) { + * return n.age; + * }); -> [{age:35,name:'ken'}] + * + ***/ + least(map: string): any[]; + least(map: (n: any) => any): any[]; + + /*** + * Maps the array to another array containing the values that + * are the result of calling on each element. + * @method map(, [scope]) + * @returns Array + * @extra [scope] is the %this% object. In addition to providing this method + * for browsers that don't support it natively, this enhanced method + * also directly accepts a string, which is a shortcut for a function + * that gets that property (or invokes a function) on each element. + * @example + * + * [1,2,3].map(function(n) { + * return n * 3; + * }); -> [3,6,9] + * ['one','two','three'].map(function(n) { + * return n.length; + * }); -> [3,3,5] + * ['one','two','three'].map('length') -> [3,3,5] + ***/ + map(map: string, scope?: any): any[]; + map(map: (n: any) => any, scope?: any): any[]; + + /*** + * Returns the element in the array with the greatest value. + * @method max([map], [all] = false) + * @returns Mixed + * @extra [map] may be a function mapping the value to be checked or a string + * acting as a shortcut. If [all] is true, will return all max values + * in an array. + * @example + * + * [1,2,3].max() -> 3 + * ['fee','fo','fum'].max('length') -> 'fee' + * ['fee','fo','fum'].max('length', true) -> ['fee'] + + [{a:3,a:2}].max(function(n) { + * return n['a']; + * }); -> {a:3} + * + ***/ + max(map: string): any; + max(map: (n: any) => any): any; + + /*** + * Returns the element in the array with the lowest value. + * @method min([map], [all] = false) + * @returns Mixed + * @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut. If [all] is true, will return all min values in an array. + * @example + * + * [1,2,3].min() -> 1 + * ['fee','fo','fum'].min('length') -> 'fo' + * ['fee','fo','fum'].min('length', true) -> ['fo'] + + ['fee','fo','fum'].min(function(n) { + * return n.length; + * }); -> ['fo'] + + [{a:3,a:2}].min(function(n) { + * return n['a']; + * }); -> [{a:2}] + * + ***/ + min(map: string): any; + min(map: (n: any) => any): any; + + /*** + * Returns the elements in the array with the most + * commonly occuring value. + * @method most([map]) + * @returns Array + * @extra [map] may be a function mapping the value to be checked or a string + * acting as a shortcut. + * @example + * + * [3,2,2].most() -> [2] + * ['fe','fo','fum'].most('length') -> ['fe','fo'] + + [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].most(function(n) { + * return n.age; + * }); -> [{age:12,name:'bob'},{age:12,name:'ted'}] + * + ***/ + most(map: string): any[]; + most(map: (n: any) => any): any[]; + + /*** + * Returns true if none of the elements in the array match . + * @method none() + * @returns Boolean + * @extra will match a string, number, array, object, or alternately test + * against a function or regex. This method implements @array_matching. + * @example + * + * [1,2,3].none(5) -> true + * ['a','b','c'].none(/b/) -> false + + [{a:1},{b:2}].none(function(n) { + * return n['a'] > 1; + * }); -> true + * + ***/ + none(f: number): bool; + none(f: string): bool; + none(f: RegExp): bool; + none(f: Object): bool; + none(f: any[]): bool; + none(f: (n: any) => bool): bool; + + /*** + * Returns a copy of the array with the elements randomized. + * @method randomize() + * @returns Array + * @extra Uses Fisher-Yates algorithm. + * @example + * + * [1,2,3,4].randomize() -> [?,?,?,?] + * + ***/ + randomize(): any[]; + + /*** + * Reduces the array to a single result. + * @method reduce(, [init]) + * @returns Mixed + * @extra If [init] is passed as a starting value, that value will be passed + * as the first argument to the callback. The second argument will be + * the first element in the array. From that point, the result of the + * callback will then be used as the first argument of the next + * iteration. This is often refered to as "accumulation", and [init] + * is often called an "accumulator". If [init] is not passed, then + * will be called n - 1 times, where n is the length of the array. + * In this case, on the first iteration only, the first argument will + * be the first element of the array, and the second argument will be + * the second. After that callbacks work as normal, using the result + * of the previous callback as the first argument of the next. This + * method is only provided for those browsers that do not support it + * natively. + * + * @example + * + * [1,2,3,4].reduce(function(a, b) { + * return a - b; + * }); + * [1,2,3,4].reduce(function(a, b) { + * return a - b; + * }, 100); + * + ***/ + reduce(fn: (a: any, b: any) => any, init: any): any; + + /*** + * Identical to %Array#reduce%, + * but operates on the elements in reverse order. + * @method reduceRight([fn], [init]) + * @returns Mixed + * @extra This method is only provided for those browsers that do not support + * it natively. + * @example + * + * [1,2,3,4].reduceRight(function(a, b) { + * return a - b; + * }); + * + ***/ + reduceRight(fn: (a: any, b: any) => any, init: any): any; + + /*** + * Removes any element in the array that matches [f1], [f2], etc. + * @method remove([f1], [f2], ...) + * @returns Array + * @extra Will match a string, number, array, object, or alternately test + * against a function or regex. This method will change the array! + * Use %exclude% for a non-destructive alias. This method implements + * @array_matching. + * @example + * + * [1,2,3].remove(3) -> [1,2] + * ['a','b','c'].remove(/b/) -> ['a','c'] + + [{a:1},{b:2}].remove(function(n) { + * return n['a'] == 1; + * }); -> [{b:2}] + * + ***/ + remove(...args: number[]): number[]; + remove(...args: string[]): string[]; + remove(...args: Object[]): Object[]; + remove(...args: any[]): any[]; + remove(fn: (n: any) => bool): any[]; + + /*** + * Removes element at . If [end] is specified, removes the range + * between and [end]. This method will change the array! + * If you don't intend the array to be changed use %clone% first. + * @method removeAt(, [end]) + * @returns Array + * @example + * + * ['a','b','c'].removeAt(0) -> ['b','c'] + * [1,2,3,4].removeAt(1, 3) -> [1] + * + ***/ + removeAt(start: number, end?: number): any[]; + + /*** + * Returns a random element from the array. + * @method sample([num]) + * @returns Mixed + * @extra If [num] is passed, will return [num] samples from the array. + * @example + * + * [1,2,3,4,5].sample() -> // Random element + * [1,2,3,4,5].sample(3) -> // Array of 3 random elements + * + ***/ + sample(): any; + sample(num: number): any[]; + + /*** + * Returns true if any element in the array matches . + * @method some(, [scope]) + * @returns Boolean + * @extra [scope] is the %this% object. %any% is provided as an alias. + * In addition to providing this method for browsers that don't + * support it natively, this method also implements @array_matching. + * @example + * + * ['a','b','c'].some(function(n) { + * return n == 'a'; + * }); + * ['a','b','c'].some(function(n) { + * return n == 'd'; + * }); + * ['a','b','c'].some('a') -> true + * [{a:2},{b:5}].some({a:2}) -> true + ***/ + some(f: number, scope?: any): bool; + some(f: string, scope?: any): bool; + some(f: any, scope?: any): bool; + some(f: (n: any) => bool, scope?: any): bool; + + /*** + * Sorts the array by . + * @method sortBy(, [desc] = false) + * @returns Array + * @extra may be a function, a string acting as a shortcut, or blank + * (direct comparison of array values). [desc] will sort the array in + * descending order. When the field being sorted on is a string, the + * resulting order will be determined by an internal collation algorithm + * that is optimized for major Western languages, but can be customized. + * For more information see @array_sorting. + * @example + * + * ['world','a','new'].sortBy('length') -> ['a','new','world'] + * ['world','a','new'].sortBy('length', true) -> ['world','new','a'] + * [{age:72},{age:13},{age:18}].sortBy(function(n) { + * return n.age; + * }); -> [{age:13},{age:18},{age:72}] + * + ***/ + sortBy(map: string, desc?: bool): any[]; + sortBy(fn: (n: any) => any, desc?: bool): any[]; + + /*** + * Subtracts from the array all elements in [a1], [a2], etc. + * @method subtract([a1], [a2], ...) + * @returns Array + * @extra This method will also correctly operate on arrays of objects. + * @example + * + * [1,3,5].subtract([5,7,9]) -> [1,3] + * [1,3,5].subtract([3],[5]) -> [1] + * ['a','b'].subtract('b','c') -> ['a'] + * + ***/ + subtract(...args: any[]): any[]; + + /*** + * @method sum([map]) + * @returns Number + * Sums all values in the array. + * @extra [map] may be a function mapping the value to be summed or a string + * acting as a shortcut. + * @example + * + * [1,2,2].sum() -> 5 + * [{age:35},{age:12},{age:12}].sum(function(n) { + * return n.age; + * }); -> 59 + * [{age:35},{age:12},{age:12}].sum('age') -> 59 + * + ***/ + sum(map: string): number; + sum(fn: (n: any) => number): number; + + /*** + * Returns a slice of the array up to . + * @method to() + * @returns Array + * @example + * + * [1,2,3].to(1) -> [1] + * [1,2,3].to(2) -> [1,2] + * + ***/ + to(index: number): any[]; + + /*** + * Returns an array containing all elements in all arrays with + * duplicates removed. + * @method union([a1], [a2], ...) + * @returns Array + * @extra This method will also correctly operate on arrays of objects. + * @example + * + * [1,3,5].union([5,7,9]) -> [1,3,5,7,9] + * ['a','b'].union(['b','c']) -> ['a','b','c'] + * + ***/ + union(array: any[]): any[]; + union(...args: any[]): any[]; + + /*** + * Removes all duplicate elements in the array. + * @method unique([map] = null) + * @returns Array + * @extra [map] may be a function mapping the value to be uniqued on or a + * string acting as a shortcut. This is most commonly used when you + * have a key that ensures the object's uniqueness, and don't need to + * check all fields. This method will also correctly operate on arrays + * of objects. + * @example + * + * [1,2,2,3].unique() -> [1,2,3] + * [{foo:'bar'},{foo:'bar'}].unique() -> [{foo:'bar'}] + + [{foo:'bar'},{foo:'bar'}].unique(function(obj){ + * return obj.foo; + * }); -> [{foo:'bar'}] + * [{foo:'bar'},{foo:'bar'}].unique('foo') -> [{foo:'bar'}] + * + ***/ + unique(map?: string): any[]; + unique(fn?: (obj: any) => any): any[]; + + /*** + * Merges multiple arrays together. + * @method zip([arr1], [arr2], ...) + * @returns Array + * @extra This method "zips up" smaller arrays into one large whose elements + * are "all elements at index 0", "all elements at index 1", etc. + * Useful when you have associated data that is split over separated + * arrays. If the arrays passed have more elements than the original + * array, they will be discarded. If they have fewer elements, the + * missing elements will filled with %null%. + * @example + * + * [1,2,3].zip([4,5,6]) -> [[1,2], [3,4], [5,6]] + * ['Martin','John'].zip(['Luther','F.'], ['King','Kennedy']) -> [['Martin','Luther','King'], ['John','F.','Kennedy']] + * + ***/ + zip(...arrays: any[]): any[][]; +} + +interface Object { + + /*** + * Creates a new object, equivalent to %new Object()% or %{}%, + * but with extended methods. + * @method Object.extended( = {}) + * @returns Extended object + * @extra See extended objects for more. + * @example + * + * Object.extended() + * Object.extended({ happy:true, pappy:false }).keys() -> ['happy','pappy'] + * Object.extended({ happy:true, pappy:false }).values() -> [true, false] + * + ***/ + extended(obj?: Object): Object; + + /*** + * Converts the query string of a URL into an object. + * @method Object.fromQueryString(, [deep] = true) + * @returns Object + * @extra If [deep] is %false%, conversion will only accept shallow params (ie. no object or arrays with %[]% syntax) as these are not universally supported. + * @example + * + * Object.fromQueryString('foo=bar&broken=wear') -> { foo: 'bar', broken: 'wear' } + * Object.fromQueryString('foo[]=1&foo[]=2') -> { foo: [1,2] } + * + ***/ + fromQueryString(str: string, deep?: bool): Object; + + /*** + * Returns true if is an object of that type. + * @method Object.is[Type]() + * @returns Boolean + * @extra %isObject% will return false on anything that is not an object + * literal, including instances of inherited classes. Note also + * that %isNaN% will ONLY return true if the object IS %NaN%. + * It does not mean the same as browser native %isNaN%, which returns + * true for anything that is "not a number". + * + * @set + * isArray + * isObject + * isBoolean + * isDate + * isFunction + * isNaN + * isNumber + * isString + * isRegExp + * + * @example + * + * Object.isArray([1,2,3]) -> true + * Object.isDate(3) -> false + * Object.isRegExp(/wasabi/) -> true + * Object.isObject({ broken:'wear' }) -> true + * + ***/ + isArray(): bool; + isArray(obj: any): bool; + isObject(): bool; + isObject(obj: any): bool; + isBoolean(): bool; + isBoolean(obj: any): bool; + isDate(): bool; + isDate(obj: any): bool; + isFunction(): bool; + isFunction(obj: any): bool; + isNaN(): bool; + isNaN(obj: any): bool; + isNumber(): bool; + isNumber(obj: any): bool; + isString(): bool; + isString(obj: any): bool; + isRegExp(): bool; + isRegExp(obj: any): bool; + + /** + * Converts the object into a query string. Accepts deep nested objects and arrays. + * If namespace is passed, it will be prefixed to all param names. + * @param obj Object to convert to a query string. + * @param namespace Namespace to prefix properties with in the query string. + * @return A query string generated from `obj` and `namespace`. + **/ + toQueryString(obj: any, namespace?: string): string; + + /*** + * Creates a clone (copy) of . + * @method clone( = {}, [deep] = false) + * @returns Cloned object + * @extra Default is a shallow clone, unless [deep] is true. %clone% + * is available as an instance method on extended objects. + * @example + * + * Object.clone({foo:'bar'}) -> { foo: 'bar' } + * Object.clone() -> {} + * Object.extended({foo:'bar'}).clone() -> { foo: 'bar' } + * + ***/ + clone(obj?: Object, deep?: bool): Object; + + /*** + * Enumerable methods in the Array package are also available to + * the Object class. They will perform their normal operations for + * every property in . + * @method [enumerable]() + * @returns Boolean + * @extra In cases where a callback is used, instead of %element, index%, + * the callback will instead be passed %key, value%. Enumerable methods + * are also available to extended objects as instance methods. + * + * @set + * each + * map + * any + * all + * none + * count + * find + * findAll + * reduce + * isEmpty + * sum + * average + * min + * max + * least + * most + * + * @example + * + * Object.any({foo:'bar'}, 'bar') -> true + * Object.extended({foo:'bar'}).any('bar') -> true + * Object.isEmpty({}) -> true + * Object.map({ fred: { age: 52 } }, 'age'); -> { fred: 52 } + * + ***/ + map(map: string): Object; + map(obj: Object, map: string): Object; + map(map: (key: string, value: any) => any): Object; + map(obj: Object, map: (key: string, value: any) => any): Object; + + any(map: string): bool; + any(obj: Object, map: string): bool; + any(map: (key: string, value: any) => bool): bool; + any(obj: Object, map: (key: string, value: any) => bool): bool; + + all(map: string): bool; + all(obj: Object, map: string): bool; + all(map: (key: string, value: any) => bool): bool; + all(obj: Object, map: (key: string, value: any) => bool): bool; + + none(map: string): bool; + none(obj: Object, map: string): bool; + none(map: (key: string, value: any) => bool): bool; + none(obj: Object, map: (key: string, value: any) => bool): bool; + + count(map: string): number; + count(obj: Object, map: string): number; + count(map: (key: string, value: any) => bool): number; + count(obj: Object, map: (key: string, value: any) => bool): number; + + find(map: string): any; + find(obj: Object, map: string): any; + find(map: (key: string, value: any) => bool): any; + find(obj: Object, map: (key: string, value: any) => bool): any; + + findAll(map: string): any[]; + findAll(obj: Object, map: string): any[]; + findAll(map: (key: string, value: any) => bool): any[]; + findAll(obj: Object, map: (key: string, value: any) => bool): any[]; + + reduce(map: string, init?: any): any; + reduce(obj: Object, map: string, init?: any): any; + reduce(map: (key: string, value: any) => any, init?: any): any; + reduce(obj: Object, map: (key: string, value: any) => any, init?: any): any; + + isEmpty(): bool; + isEmpty(obj: Object): bool; + + sum(map: string): number; + sum(obj: Object, map: string): number; + sum(map: (key: string, value: any) => number): number; + sum(obj: Object, map: (key: string, value: any) => number): number; + + average(map: string): number; + average(obj: Object, map: string): number; + average(map: (key: string, value: any) => number): number; + average(obj: Object, map: (key: string, value: any) => number): number; + + min(map: string): Object; + min(obj: Object, map: string): Object; + min(map: (key: string, value: any) => any): Object; + min(obj: Object, map: (key: string, value: any) => any): Object; + + max(map: string): Object; + max(obj: Object, map: string): Object; + max(map: (key: string, value: any) => any): Object; + max(obj: Object, map: (key: string, value: any) => any): Object; + + least(map: string): Object; + least(obj: Object, map: string): Object; + least(map: (key: string, value: any) => any): Object; + least(obj: Object, map: (key: string, value: any) => any): Object; + + most(map: string): Object; + most(obj: Object, map: string): Object; + most(map: (key: string, value: any) => any): Object; + most(obj: Object, map: (key: string, value: any) => any): Object; + + /*** + * Returns true if
and are equal. + * @method equal(, ) + * @returns Boolean + * @extra %equal% in Sugar is "egal", meaning the values are equal + * if they are "not observably distinguishable". Note that on + * extended objects the name is %equals% for readability. + * @example + * + * Object.equal({a:2}, {a:2}) -> true + * Object.equal({a:2}, {a:3}) -> false + * Object.extended({a:2}).equals({a:3}) -> false + * + ***/ + equal(a: Object, b: Object): bool; + + /*** + * Checks if has using hasOwnProperty from Object.prototype. + * @method has(, ) + * @returns Boolean + * @extra This method is considered safer than %Object#hasOwnProperty% when + * using objects as hashes. See + * http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ + * for more. + * @example + * + * Object.has({ foo: 'bar' }, 'foo') -> true + * Object.has({ foo: 'bar' }, 'baz') -> false + * Object.has({ hasOwnProperty: true }, 'foo') -> false + * + ***/ + has(key: string): bool; + has(obj: Object, key: string): bool; + + /*** + * Returns an array containing the keys in . Optionally calls + * [fn] for each key. + * @method keys(, [fn]) + * @returns Array + * @extra This method is provided for browsers that don't support it natively, + * and additionally is enhanced to accept the callback [fn]. Returned + * keys are in no particular order. %keys% is available as an instance + * method on extended objects. + * @example + * + * Object.keys({ broken: 'wear' }) -> ['broken'] + * Object.keys({ broken: 'wear' }, function(key, value) { + * // Called once for each key. + * }); + * Object.extended({ broken: 'wear' }).keys() -> ['broken'] + * + ***/ + keys(): string[]; + keys(obj: Object, fn?: (key: string, value: any) => void ): string[]; + + /*** + * Merges all the properties of into . + * @method merge(, , [deep] = false, [resolve] = true) + * @returns Merged object + * @extra Merges are shallow unless [deep] is %true%. Properties of + * will win in the case of conflicts, unless [resolve] is %false%. + * [resolve] can also be a function that resolves the conflict. + * In this case it will be passed 3 arguments, %key%, %targetVal%, + * and %sourceVal%, with the context set to . This will allow + * you to solve conflict any way you want, ie. adding two numbers + * together, etc. %merge% is available as an instance method on + * extended objects. + * @example + * + * Object.merge({a:1},{b:2}) -> { a:1, b:2 } + * Object.merge({a:1},{a:2}, false, false) -> { a:1 } + + Object.merge({a:1},{a:2}, false, function(key, a, b) { + * return a + b; + * }); -> { a:3 } + * Object.extended({a:1}).merge({b:2}) -> { a:1, b:2 } + * + ***/ + merge(target: Object, source: Object, deep?: bool, resolve?: bool): Object; + merge(target: Object, source: Object, deep?: bool, resolve?: (key: string, targetVal: any, sourceVal: any) => any): Object; + + /** + * Builds a new object containing all values except those specified in find. + * When find is a string, that single key will be rejected. It can also be a regex, + * rejecting any key that matches, or an object which will match if the key also + * exists in that object, effectively "subtracting" that object. Multiple selections + * may also be passed as an array or directly as enumerated arguments. reject is + * available as an instance method on extended objects. + * @param obj Object to remove the properties in `find`. + * @param find The property (string), properties (object) or RegExp to remove from `obj`. + * @return Modified `obj` with `find` properties removed. + **/ + reject(obj: any, ...find: any): any; + + /** + * Builds a new object containing the values specified in find. When find is a string, + * that single key will be selected. It can also be a regex, selecting any key that + * matches, or an object which will match if the key also exists in that object, + * effectively doing an "intersect" operation on that object. Multiple selections + * may also be passed as an array or directly as enumerated arguments. select is + * available as an instance method on extended objects. + * @param obj Object to keep the properties in `find`. + * @param find The property (string), properties (object) or RegExp to keep on `obj`. + * @return Modified `obj` with only the `find` properties remaining. + **/ + select(obj: any, ...find: any[]): any; + + + /*** + * Returns the number of properties in . + * @method size() + * @returns Number + * @extra %size% is available as an instance method on extended objects. + * @example + * + * Object.size({ foo: 'bar' }) -> 1 + * + ***/ + size(): number; + size(obj: Object): number; + + /*** + * Runs and returns . + * @method tap(, ) + * @returns Object + * @extra A string can also be used as a shortcut to a method. This method + * is used to run an intermediary function in the middle of method + * chaining. As a standalone method on the Object class it doesn't + * have too much use. The power of %tap% comes when using extended + * objects or modifying the Object prototype with Object.extend(). + * @example + * + * Object.extend(); + * [2,4,6].map(Math.exp).tap(function(arr) { + * arr.pop() + * }); + * [2,4,6].map(Math.exp).tap('pop').map(Math.round); -> [7,55] + * + ***/ + tap(fn: string): Object; + tap(fn: (...args: any[]) => any): Object; + tap(obj: Object, fn: string): Object; + tap(obj: Object, fn: (...args: any[]) => any): Object; + + /*** + * Returns an array containing the values in . + * Optionally calls [fn] for each value. + * @method values(, [fn]) + * @returns Array + * @extra Returned values are in no particular order. %values% is available + * as an instance method on extended objects. + * @example + * + * Object.values({ broken: 'wear' }) -> ['wear'] + * Object.values({ broken: 'wear' }, function(value) { + * // Called once for each value. + * }); + * Object.extended({ broken: 'wear' }).values() -> ['wear'] + * + ***/ + values(): any[]; + values(fn: (value: any) => any): any[]; + values(obj: Object): any[]; + values(obj: Object, fn: (value: any) => any): any[]; + + /*** + * Watches a property of and runs when it changes. + * @method watch(, , ) + * @returns Nothing + * @extra is passed three arguments: the property , the old value, + * and the new value. The return value of [fn] will be set as the new + * value. This method is useful for things such as validating or cleaning + * the value when it is set. Warning: this method WILL NOT work in + * browsers that don't support %Object.defineProperty%. This notably + * includes IE 8 and below, and Opera. This is the only method in Sugar + * that is not fully compatible with all browsers. %watch% is available + * as an instance method on extended objects. + * @example + * + * Object.watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) { + * // Will be run when the property 'foo' is set on the object. + * }); + * Object.extended().watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) { + * // Will be run when the property 'foo' is set on the object. + * }); + * + ***/ + watch(prop: string, fn: (prop: string, oldVal: any, newVal: any) => any): void; + watch(obj: Object, prop: string, fn: (prop: string, oldVal: any, newVal: any) => any): void; +} + +interface Function { + + /*** + * Creates a function that will execute after [num] calls. + * @method after([num] = 1) + * @returns Function + * @extra %after% is useful for running a final callback after a series of + * asynchronous operations, when the order in which the operations will + * complete is unknown. + * @example + * + * var fn = (function() { + * // Will be executed once only + * }).after(3); fn(); fn(); fn(); + * + ***/ + after(num?: number): Function; + + /*** + * Binds as the %this% object for the function when it is called. + * Also allows currying an unlimited number of parameters. + * @method bind(, [arg1], ...) + * @returns Function + * @extra "currying" means setting parameters ([arg1], [arg2], etc.) ahead of + * time so that they are passed when the function is called later. + * If you pass additional parameters when the function is actually + * called, they will be added will be added to the end of the curried + * parameters. This method is provided for browsers that don't support + * it internally. + * @example + * + + (function() { + * return this; + * }).bind('woof')(); -> returns 'woof'; function is bound with 'woof' as the this object. + * (function(a) { + * return a; + * }).bind(1, 2)(); -> returns 2; function is bound with 1 as the this object and 2 curried as the first parameter + * (function(a, b) { + * return a + b; + * }).bind(1, 2)(3); -> returns 5; function is bound with 1 as the this object, 2 curied as the first parameter and 3 passed as the second when calling the function + * + ***/ + bind(scope?: Object, ...args: any[]): Function; + + /*** + * Cancels a delayed function scheduled to be run. + * @method cancel() + * @returns Function + * @extra %delay%, %lazy%, %throttle%, and %debounce% can all set delays. + * @example + * + * (function() { + * alert('hay'); // Never called + * }).delay(500).cancel(); + * + ***/ + cancel(): Function; + + /*** + * Creates a "debounced" function that postpones its execution until + * after milliseconds have passed. + * @method debounce() + * @returns Function + * @extra This method is useful to execute a function after things have + * "settled down". A good example of this is when a user tabs quickly + * through form fields, execution of a heavy operation should happen + * after a few milliseconds when they have "settled" on a field. + * @example + * + * var fn = (function(arg1) { + * // called once 50ms later + * }).debounce(50); fn() fn() fn(); + * + ***/ + debounce(ms: number): Function; + + /*** + * Executes the function after milliseconds. + * @method delay([ms] = 0, [arg1], ...) + * @returns Function + * @extra Returns a reference to itself. %delay% is also a way to execute + * non-blocking operations that will wait until the CPU is free. + * Delayed functions can be canceled using the %cancel% method. + * Can also curry arguments passed in after . + * @example + * + * (function(arg1) { + * // called 1s later + * }).delay(1000, 'arg1'); + * + ***/ + delay(ms?: number, ...args: any[]): Function; + + /*** + * Returns a new version of the function which when called will have + * some of its arguments pre-emptively filled in, also known as "currying". + * @method fill(, , ...) + * @returns Function + * @extra Arguments passed to a "filled" function are generally appended to + * the curried arguments. However, if %undefined% is passed as any of + * the arguments to %fill%, it will be replaced, when the "filled" + * function is executed. This allows currying of arguments even when + * they occur toward the end of an argument list (the example + * demonstrates this much more clearly). + * @example + * + * var delayOneSecond = setTimeout.fill(undefined, 1000); + * delayOneSecond(function() { + * // Will be executed 1s later + * }); + * + ***/ + fill(...args: any[]): Function; + + /*** + * Creates a lazy function that, when called repeatedly, will queue + * execution and wait [ms] milliseconds to execute again. + * @method lazy([ms] = 1, [limit] = Infinity) + * @returns Function + * @extra Lazy functions will always execute as many times as they are called + * up to [limit], after which point subsequent calls will be ignored + * (if it is set to a finite number). Compare this to %throttle%, which + * will execute only once per [ms] milliseconds. %lazy% is useful when + * you need to be sure that every call to a function is executed, but + * in a non-blocking manner. Calling %cancel% on a lazy function will + * clear the entire queue. Note that [ms] can also be a fraction. + * @example + * + * (function() { + * // Executes immediately. + * }).lazy()(); + * (3).times(function() { + * // Executes 3 times, with each execution 20ms later than the last. + * }.lazy(20)); + * (100).times(function() { + * // Executes 50 times, with each execution 20ms later than the last. + * }.lazy(20, 50)); + * + ***/ + lazy(ms?: number, limit?: number): Function; + + /*** + * Creates a function that will execute only once and store the result. + * @method once() + * @returns Function + * @extra %once% is useful for creating functions that will cache the result of + * an expensive operation and use it on subsequent calls. Also it can be + * useful for creating initialization functions that only need to be run + * once. + * @example + * + * var fn = (function() { + * // Will be executed once only + * }).once(); fn(); fn(); fn(); + * + ***/ + once(): Function; + + /*** + * Creates a "throttled" version of the function that will only be + * executed once per milliseconds. + * @method throttle() + * @returns Function + * @extra This is functionally equivalent to calling %lazy% with a [limit] + * of %1%. %throttle% is appropriate when you want to make sure a + * function is only executed at most once for a given duration. + * Compare this to %lazy%, which will queue rapid calls and execute + * them later. + * @example + * + * (3).times(function() { + * // called only once. will wait 50ms until it responds again + * }.throttle(50)); + * + ***/ + throttle(ms: number): Function; +} + +interface RegExp { + + /*** + * Escapes all RegExp tokens in a string. + * @method RegExp.escape( = '') + * @returns String + * @example + * + * RegExp.escape('really?') -> 'really\?' + * RegExp.escape('yes.') -> 'yes\.' + * RegExp.escape('(not really)') -> '\(not really\)' + * + ***/ + escape(str: string): string; + + /*** + * Adds to the regex. + * @method addFlag() + * @returns RegExp + * @example + * + * /texty/.addFlag('g') -> now has global flag set + * + ***/ + addFlag(flag: string): RegExp; + + /*** + * Returns the flags of the regex as a string. + * @method getFlags() + * @returns String + * @example + * + * /texty/gim.getFlags('testy') -> 'gim' + * + ***/ + getFlags(): string; + + /*** + * Removes from the regex. + * @method removeFlag() + * @returns RegExp + * @example + * + * /texty/g.removeFlag('g') -> now has global flag removed + * + ***/ + removeFlag(flag: string): RegExp; + + /*** + * Sets the flags on a regex and retuns a copy. + * @method setFlags() + * @returns RegExp + * @example + * + * /texty/.setFlags('gim') -> now has global, ignoreCase, and multiline set + * + ***/ + setFlags(flags: string): RegExp; +} + +interface Locale { + plural: bool; + months: string; + weekdays: string; + units: string; + numbers: string; + tokens: string[]; + short: string; + long: string; + full: string; + past: string; + future: string; + duration: string; + timeMarker: string; + ampm: string; + modifiers: + { + name: string; + src: string; + value: number; + }[]; + dateParse: string[]; + timeParse: string[]; +} + +interface Date { + + /*** + * Adds a locale to the locales understood by Sugar. + * @method Date.addLocale(, ) + * @returns Locale + * @extra For more see @date_format. + ***/ + addLocale(code: string, set: Locale): Locale; + + /*** + * Alternate Date constructor which understands many different text formats, + * a timestamp, or another date. + * @method Date.create(, [locale] = currentLocale) + * @returns Date + * @extra If no argument is given, date is assumed to be now. %Date.create% additionally + * can accept enumerated parameters as with the standard date constructor. [locale] + * can be passed to specify the locale that the date is in. When unspecified, the + * current locale (default is English) is assumed. UTC-based dates can be created + * through the %utc% object. For more see @date_format. + * @set + * Date.utc.create + * + * @example + * + * Date.create('July') -> July of this year + * Date.create('1776') -> 1776 + * Date.create('today') -> today + * Date.create('wednesday') -> This wednesday + * Date.create('next friday') -> Next friday + * Date.create('July 4, 1776') -> July 4, 1776 + * Date.create(-446806800000) -> November 5, 1955 + * Date.create(1776, 6, 4) -> July 4, 1776 + * Date.create('1776?07?04?', 'ja') -> July 4, 1776 + * Date.utc.create('July 4, 1776', 'en') -> July 4, 1776 + * + ***/ + create(locale?: string): Date; + create(d: string, locale?: string): Date; + create(year: number, month: number, day: number, locale?: string): Date; + + /*** + * Alternate form of %Date.create% with any ambiguity assumed to be the future. + * @method Date.future(, [locale] = currentLocale) + * @returns Date + * @extra For example %"Sunday"% can be either "the Sunday coming up" or "the Sunday last" + * depending on context. Note that dates explicitly in the past ("last Sunday") will + * remain in the past. This method simply provides a hint when ambiguity exists. UTC + * -based dates can be created through the %utc% object. For more, see @date_format. + * @set + * Date.utc.future + * + * @example + * + * Date.future('July') -> July of this year or next depending on the current month + * Date.future('Wednesday') -> This wednesday or next depending on the current weekday + * + ***/ + future(d: string, locale?: string): Date; + + /*** + * Gets the locale for the given code, or the current locale. + * @method Date.getLocale([code] = current) + * @returns Locale + * @extra The resulting locale object can be manipulated to provide more control over date localizations. + * For more about locales, see @date_format. + ***/ + getLocale(code?: string): Locale; + + /*** + * Returns the number of milliseconds since January 1st, 1970 00:00:00 (UTC time). + * @method Date.now() + * @returns String + * @extra Provided for browsers that do not support this method. + * @example + * + * Date.now() -> ex. 1311938296231 + * + ***/ + now(): string; + + /*** + * Alternate form of %Date.create% with any ambiguity assumed to be the past. + * @method Date.past(, [locale] = currentLocale) + * @returns Date + * @extra For example %"Sunday"% can be either "the Sunday coming up" or "the Sunday last" depending + * on context. Note that dates explicitly in the future ("next Sunday") will remain in the future. + * This method simply provides a hint when ambiguity exists. UTC-based dates can be created + * through the %utc% object. For more, see @date_format. + * @set + * Date.utc.past + * @example + * + * Date.past('July') -> July of this year or last depending on the current month + * Date.past('Wednesday') -> This wednesday or last depending on the current weekday + * + ***/ + past(d: string, local?: string): Date; + + /*** + * Creates a new date range. + * @method Date.range([start], [end]) + * @returns DateRange + * @extra If either [start] or [end] are null, they will default to the current date. + ***/ + range(start: Date, end: Date): DateRange; + + /*** + * Sets the current locale to be used with dates. + * @method Date.setLocale() + * @returns Locale + * @extra Sugar has support for 13 locales that are available through the + & "Date Locales" package. In addition you can define a new locale with + * %Date.addLocale%. For more see @date_format. + * + ***/ + setLocale(code: string): Locale; + + /*** + * Adds of the unit to the date. If [reset] is true, all lower + * units will be reset. + * @method add[Units](, [reset] = false) + * @returns Date + * @extra Note that "months" is ambiguous as a unit of time. If the target + * date falls on a day that does not exist (ie. August 31 -> February 31), + * the date will be shifted to the last day of the month. Don't use + * %addMonths% if you need precision. + * + * @set + * addMilliseconds + * addSeconds + * addMinutes + * addHours + * addDays + * addWeeks + * addMonths + * addYears + * + * @example + * + * Date.create().addMilliseconds(5) -> current time + 5 milliseconds + * Date.create().addDays(5) -> current time + 5 days + * Date.create().addYears(5) -> current time + 5 years + * + ***/ + addMilliseconds(num: number, reset?: bool): Date; + addSeconds(num: number, reset?: bool): Date; + addMinutes(num: number, reset?: bool): Date; + addHours(num: number, reset?: bool): Date; + addDays(num: number, reset?: bool): Date; + addWeeks(num: number, reset?: bool): Date; + addMonths(num: number, reset?: bool): Date; + addYears(num: number, reset?: bool): Date; + + /*** + * Sets the date forward. + * @method advance(, [reset] = false) + * @returns Date + * @extra This method can accept multiple formats including an object, a string + * in the format %3 days%, a single number as milliseconds, or enumerated + * parameters (as with the Date constructor). If [reset] is %true%, any + * units more specific than those passed will be reset. For more see + * @date_format. + * @example + * + * new Date().advance({ year: 2 }) -> 2 years in the future + * new Date().advance('2 days') -> 2 days in the future + * new Date().advance(0, 2, 3) -> 2 months 3 days in the future + * new Date().advance(86400000) -> 1 day in the future + * + ***/ + advance(set: string, reset?: bool): Date; + advance(year: number, month: number, day: number, reset?: bool): Date; + advance(milliseconds: number, reset?: bool): Date; + advance(set: Object, reset?: bool): Date; + + /*** + * Sets the date to the beginning of the appropriate unit. + * @method beginningOf[Unit]() + * @returns Date + * + * @set + * beginningOfDay + * beginningOfWeek + * beginningOfMonth + * beginningOfYear + * + * @example + * + * Date.create().beginningOfDay() -> the beginning of today (resets the time) + * Date.create().beginningOfWeek() -> the beginning of the week + * Date.create().beginningOfMonth() -> the beginning of the month + * Date.create().beginningOfYear() -> the beginning of the year + * + ***/ + beginningOfDay(): Date; + beginningOfWeek(): Date; + beginningOfMonth(): Date; + beginningOfYear(): Date; + + /*** + * Clones the date. + * @method clone() + * @returns Date + * @example + * + * Date.create().clone() -> Copy of now + * + ***/ + clone(): Date; + + /*** + * Returns the number of days in the date's month. + * @method daysInMonth() + * @returns Number + * @example + * + * Date.create('May').daysInMonth() -> 31 + * Date.create('February, 2000').daysInMonth() -> 29 + * + ***/ + daysInMonth(): number; + + /*** + * Sets the date to the end of the appropriate unit. + * @method endOf[Unit]() + * @returns Date + * + * @set + * endOfDay + * endOfWeek + * endOfMonth + * endOfYear + * + * @example + * + * Date.create().endOfDay() -> the end of today (sets the time to 23:59:59.999) + * Date.create().endOfWeek() -> the end of the week + * Date.create().endOfMonth() -> the end of the month + * Date.create().endOfYear() -> the end of the year + * + ***/ + endOfDay(): Date; + endOfWeek(): Date; + endOfMonth(): Date; + endOfYear(): Date; + + /*** + * Formats and outputs the date. + * @method format(, [locale] = currentLocale) + * @returns String + * @extra can be a number of pre-determined formats or a string of + * tokens. Locale-specific formats are %short%, %long%, and %full% which + * have their own aliases and can be called with %date.short()%, etc. + * If is not specified the %long% format is assumed. [locale] + * specifies a locale code to use (if not specified the current locale + * is used). See @date_format for more details. + * + * @set + * short + * long + * full + * + * @example + * + * Date.create().format() -> ex. July 4, 2003 + * Date.create().format('{Weekday} {d} {Month}, {yyyy}') -> ex. Monday July 4, 2003 + * Date.create().format('{hh}:{mm}') -> ex. 15:57 + * Date.create().format('{12hr}:{mm}{tt}') -> ex. 3:57pm + * Date.create().format(Date.ISO8601_DATETIME) -> ex. 2011-07-05 12:24:55.528Z + * Date.create('last week').format('short', 'ja') -> ex. ?? + * Date.create('yesterday').format(function(value,unit,ms,loc) { + * // value = 1, unit = 3, ms = -86400000, loc = [current locale object] + * }); -> ex. 1 day ago + * + ***/ + format(format: string, locale?: string): string; + short(): string; + long(): string; + full(): string; + + /*** + * Returns a string representation of the offset from UTC time. If [iso] + * is true the offset will be in ISO8601 format. + * @method getUTCOffset([iso]) + * @returns String + * @example + * + * new Date().getUTCOffset() -> "+0900" + * new Date().getUTCOffset(true) -> "+09:00" + * + ***/ + getUTCOffset(iso?: bool): string; + + /*** + * Gets the date's week (of the year). + * @returns The date's week of the year as defined by the ISO-8601 standard. + * @extra If %utc% is set on the date, the week will be according to UTC time. + * + * @example + * + * new Date().getWeek() -> today's week of the year + * + ***/ + getISOWeek(): number; + + /*** + * Alias for %getDay%. + * @method getWeekday() + * @returns Number + * @set + * getUTCWeekday + * + * @example + * + * Date.create().getWeekday(); -> (ex.) 3 + * Date.create().getUTCWeekday(); -> (ex.) 3 + * + ***/ + getWeekday(): number; + getUTCWeekday(): number; + getDay(): number; + getUTCDay(): number; + + /*** + * Returns true if the date is . + * @method is(, [margin] = 0) + * @returns Boolean + * @extra will accept a date object, timestamp, or text format. %is% + * additionally understands more generalized expressions like + * month/weekday names, 'today', etc, and compares to the precision + * implied in . [margin] allows an extra margin of error in + * milliseconds. For more, see @date_format. + * @example + * + * Date.create().is('July') -> true or false? + * Date.create().is('1776') -> false + * Date.create().is('today') -> true + * Date.create().is('weekday') -> true or false? + * Date.create().is('July 4, 1776') -> false + * Date.create().is(-6106093200000) -> false + * Date.create().is(new Date(1776, 6, 4)) -> false + * + ***/ + is(d: string, margin?: number): bool; + is(milliseconds: number, margin?: number): bool; + is(d: Date, margin?: number): bool; + + /*** + * Returns true if the date is after the . + * @method isAfter(, [margin] = 0) + * @returns Boolean + * @extra [margin] is to allow extra margin of error (in ms). will accept + * a date object, timestamp, or text format. If not specified, is + * assumed to be now. See @date_format for more. + * @example + * + * new Date().isAfter('tomorrow') -> false + * new Date().isAfter('yesterday') -> true + * + ***/ + isAfter(d: string, margin?: number): bool; + isAfter(milliseconds: number, margin?: number): bool; + isAfter(d: Date, margin?: number): bool; + + /*** + * Returns true if the date is before . + * @method isBefore(, [margin] = 0) + * @returns Boolean + * @extra [margin] is to allow extra margin of error (in ms). will accept + * a date object, timestamp, or text format. If not specified, is + * assumed to be now. See @date_format for more. + * @example + * + * new Date().isBefore('tomorrow') -> true + * new Date().isBefore('yesterday') -> false + * + ***/ + isBefore(d: string, margin?: number): bool; + isBefore(milliseconds: number, margin?: number): bool; + isBefore(d: Date, margin?: number): bool; + + /*** + * Returns true if the date falls between and . + * @method isBetween(, , [margin] = 0) + * @returns Boolean + * @extra [margin] is to allow extra margin of error (in ms). and + * will accept a date object, timestamp, or text format. If not specified, + * they are assumed to be now. See @date_format for more. + * @example + * + * new Date().isBetween('yesterday', 'tomorrow') -> true + * new Date().isBetween('last year', '2 years ago') -> false + * + ***/ + isBefore(start: string, end: string, margin?: number): bool; + isBefore(start: number, end: string, margin?: number): bool; + isBefore(start: Date, end: Date, margin?: number): bool; + + /*** + * Returns true if the date falls on that day. + * @method is[Day]() + * @returns Boolean + * @extra Also available: %isYesterday%, %isToday%, %isTomorrow%, %isWeekday%, + * and %isWeekend%. + * + * @set + * isToday + * isYesterday + * isTomorrow + * isWeekday + * isWeekend + * isSunday + * isMonday + * isTuesday + * isWednesday + * isThursday + * isFriday + * isSaturday + * + * @example + * + * Date.create('tomorrow').isToday() -> false + * Date.create('thursday').isTomorrow() -> ? + * Date.create('yesterday').isWednesday() -> ? + * Date.create('today').isWeekend() -> ? + * + ***/ + isToday(): bool; + isYesterday(): bool; + isTomorrow(): bool; + isWeekday(): bool; + isWeekend(): bool; + isSunday(): bool; + isMonday(): bool; + isTuesday(): bool; + isWednesday(): bool; + isThursday(): bool; + isFriday(): bool; + isSaturday(): bool; + + /*** + * Returns true if the date is in the future. + * @method isFuture() + * @returns Boolean + * @example + * + * Date.create('next week').isFuture() -> true + * Date.create('last week').isFuture() -> false + * + ***/ + isFuture(): bool; + + /*** + * Returns true if the date is last week/month/year. + * @method isLast[Unit]() + * @returns Boolean + * + * @set + * isLastWeek + * isLastMonth + * isLastYear + * + * @example + * + * Date.create('yesterday').isLastWeek() -> true or false? + * Date.create('yesterday').isLastMonth() -> probably not... + * Date.create('yesterday').isLastYear() -> even less likely... + * + ***/ + isLastWeek(): bool; + isLastMonth(): bool; + isLastYear(): bool; + + /*** + * Returns true if the date is a leap year. + * @method isLeapYear() + * @returns Boolean + * @example + * + * Date.create('2000').isLeapYear() -> true + * + ***/ + isLeapYear(): bool; + + /*** + * Returns true if the date is next week/month/year. + * @method isNext[Unit]() + * @returns Boolean + * + * @set + * isNextWeek + * isNextMonth + * isNextYear + * + * @example + * + * Date.create('tomorrow').isNextWeek() -> true or false? + * Date.create('tomorrow').isNextMonth() -> probably not... + * Date.create('tomorrow').isNextYear() -> even less likely... + * + ***/ + isNextWeek(): bool; + isNextMonth(): bool; + isNextYear(): bool; + + /*** + * Returns true if the date is in the past. + * @method isPast() + * @returns Boolean + * @example + * + * Date.create('last week').isPast() -> true + * Date.create('next week').isPast() -> false + * + ***/ + isPast(): bool; + + /*** + * Returns true if the date is this week/month/year. + * @method isThis[Unit]() + * @returns Boolean + * + * @set + * isThisWeek + * isThisMonth + * isThisYear + * + * @example + * + * Date.create('tomorrow').isThisWeek() -> true or false? + * Date.create('tomorrow').isThisMonth() -> probably... + * Date.create('tomorrow').isThisYear() -> signs point to yes... + * + ***/ + isThisWeek(): bool; + isThisMonth(): bool; + isThisYear(): bool; + + /*** + * Returns true if the date has no timezone offset. + * @method isUTC() + * @returns Boolean + * @extra This will also return true for a date that has had %toUTC% called on it. This is intended to help approximate shifting timezones which is not possible in client-side Javascript. Note that the native method %getTimezoneOffset% will always report the same thing, even if %isUTC% becomes true. + * @example + * + * new Date().isUTC() -> true or false? + * new Date().toUTC().isUTC() -> true + * + ***/ + isUTC(): bool; + + /*** + * Returns true if the date is valid. + * @method isValid() + * @returns Boolean + * @example + * + * new Date().isValid() -> true + * new Date('flexor').isValid() -> false + * + ***/ + isValid(): bool; + + /*** + * @method iso() + * @method toISOString() + * @returns String + * Formats the string to ISO8601 format. + * @extra This will always format as UTC time. Provided for browsers that do not + * support this method. + * @example + * + * Date.create().toISOString() -> ex. 2011-07-05 12:24:55.528Z + * + ***/ + iso(): string; + toISOString(): string; + + /*** + * Returns a relative date string offset to the current time. + * @method relative([fn], [locale] = currentLocale) + * @returns String + * @extra [fn] can be passed to provide for more granular control over the + * resulting string. [fn] is passed 4 arguments: the adjusted value, + * unit, offset in milliseconds, and a localization object. As an + * alternate syntax, [locale] can also be passed as the first (and only) + * parameter. For more, see @date_format. + * @example + * + * Date.create('90 seconds ago').relative() -> 1 minute ago + * Date.create('January').relative() -> ex. 5 months ago + * Date.create('January').relative('ja') -> 3??? + * Date.create('120 minutes ago').relative(function(val,unit,ms,loc) { + * // value = 2, unit = 3, ms = -7200, loc = [current locale object] + * }); -> ex. 5 months ago + * + ***/ + relative(locale: string): string; + relative(fn?: (value: number, unit: string, ms: number, loc: Locale) => string, locale?: string): string; + + /*** + * Resets the unit passed and all smaller units. Default is "hours", + * effectively resetting the time. + * @method reset([unit] = 'hours') + * @returns Date + * @example + * + * Date.create().reset('day') -> Beginning of today + * Date.create().reset('month') -> 1st of the month + * + ***/ + reset(unit?: string): Date; + + /*** + * Sets the date back. + * @method rewind(, [reset] = false) + * @returns Date + * @extra This method can accept multiple formats including a single number as a + * timestamp, an object, or enumerated parameters (as with the Date + * constructor). If [reset] is %true%, any units more specific than + * those passed will be reset. For more see @date_format. + * @example + * + * new Date().rewind({ year: 2 }) -> 2 years in the past + * new Date().rewind(0, 2, 3) -> 2 months 3 days in the past + * new Date().rewind(86400000) -> 1 day in the past + * + ***/ + rewind(ms: number, reset?: bool): Date; + rewind(year: number, month: number, day: number, reset?: bool): Date; + //rewind(d: Object, reset?: bool): Date; // Do not like this, is not typesafe + + /*** + * Sets the date object. + * @method set(, [reset] = false) + * @returns Date + * @extra This method can accept multiple formats including a single number as a + * timestamp, an object, or enumerated parameters (as with the Date + * constructor). If [reset] is %true%, any units more specific than those + * passed will be reset. + * + * @example + * + * new Date().set({ year: 2011, month: 11, day: 31 }) -> December 31, 2011 + * new Date().set(2011, 11, 31) -> December 31, 2011 + * new Date().set(86400000) -> 1 day after Jan 1, 1970 + * new Date().set({ year: 2004, month: 6 }, true) -> June 1, 2004, 00:00:00.000 + * + ***/ + set (ms: number): Date; + set (year: number, month: number, day: number): Date; + //set(d: Object, reset?: bool): Date; // Do not like this, is not typesafe + + + /*** + * Sets the week (of the year). + * @example + * + * d = new Date(); d.setWeek(15); d; -> 15th week of the year + * + ***/ + setISOWeek(week: number): void; + + /*** + * Sets the weekday of the date. + * @method setWeekday() + * @returns Nothing + * + * @example + * + * d = new Date(); d.setWeekday(1); d; -> Monday of this week + * d = new Date(); d.setWeekday(6); d; -> Saturday of this week + * + ***/ + setWeekday(day: number): void; + + /*** + * Returns a JSON representation of the date. + * @method toJSON() + * @returns String + * @extra This is effectively an alias for %toISOString%. Will always return + * the date in UTC time. Provided for browsers that do not support this + * method. + * @example + * + * Date.create().toJSON() -> ex. 2011-07-05 12:24:55.528Z + * + ***/ + toJSON(): string; + + /*** + * Returns the time ago in the appropriate unit. + * @method [units]Ago() + * @returns Number + * + * @set + * millisecondsAgo + * secondsAgo + * minutesAgo + * hoursAgo + * daysAgo + * weeksAgo + * monthsAgo + * yearsAgo + * + * @example + * + * Date.create('last year').millisecondsAgo() -> 3,600,000 + * Date.create('last year').daysAgo() -> 7 + * Date.create('last year').yearsAgo() -> 15 + * + ***/ + millisecondsAgo(): number; + secondsAgo(): number; + minutesAgo(): number; + hoursAgo(): number; + daysAgo(): number; + weeksAgo(): number; + monthsAgo(): number; + yearsAgo(): number; + + /*** + * Returns the time from now in the appropriate unit. + * @method [units]FromNow() + * @returns Number + * + * @set + * millisecondsFromNow + * secondsFromNow + * minutesFromNow + * hoursFromNow + * daysFromNow + * weeksFromNow + * monthsFromNow + * yearsFromNow + * + * @example + * + * Date.create('next year').millisecondsFromNow() -> 3,600,000 + * Date.create('next year').daysFromNow() -> 7 + * Date.create('next year').yearsFromNow() -> 15 + * + ***/ + millisecondsFromNow(): number; + secondsFromNow(): number; + minutesFromNow(): number; + hoursFromNow(): number; + daysFromNow(): number; + weeksFromNow(): number; + monthsFromNow(): number; + yearsFromNow(): number; + + /*** + * Returns the time since [d] in the appropriate unit. + * @method [units]Since([d], [locale] = currentLocale) + * @returns Number + * @extra [d] will accept a date object, timestamp, or text format. If not + * specified, [d] is assumed to be now. [locale] can be passed to specify + * the locale that the date is in. %[unit]Ago% is provided as an alias to + * make this more readable when [d] is assumed to be the current date. + * For more see @date_format. + * + * @set + * millisecondsSince + * secondsSince + * minutesSince + * hoursSince + * daysSince + * weeksSince + * monthsSince + * yearsSince + * + * @example + * + * Date.create().millisecondsSince('1 hour ago') -> 3,600,000 + * Date.create().daysSince('1 week ago') -> 7 + * Date.create().yearsSince('15 years ago') -> 15 + * Date.create('15 years ago').yearsAgo() -> 15 + * + ***/ + millisecondsSince(date?: Date, locale?: string): number; + millisecondsSince(date: string, locale?: string): number; + secondsSince(date?: Date, locale?: string): number; + secondsSince(date: string, locale?: string): number; + minutesSince(date?: Date, locale?: string): number; + minutesSince(date: string, locale?: string): number; + hoursSince(date?: Date, locale?: string): number; + hoursSince(date: string, locale?: string): number; + daysSince(date?: Date, locale?: string): number; + daysSince(date: string, locale?: string): number; + weeksSince(date?: Date, locale?: string): number; + weeksSince(date: string, locale?: string): number; + monthsSince(date?: Date, locale?: string): number; + monthsSince(date: string, locale?: string): number; + yearsSince(date?: Date, locale?: string): number; + yearsSince(date: string, locale?: string): number; + + /*** + * Returns the time until [d] in the appropriate unit. + * @method [units]Until([d], [locale] = currentLocale) + * @returns Number + * @extra [d] will accept a date object, timestamp, or text format. If not + * specified, [d] is assumed to be now. [locale] can be passed to specify + * the locale that the date is in. %[unit]FromNow% is provided as an + * alias to make this more readable when [d] is assumed to be the current + * date. For more see @date_format. + * + * @set + * millisecondsUntil + * secondsUntil + * minutesUntil + * hoursUntil + * daysUntil + * weeksUntil + * monthsUntil + * yearsUntil + * + * @example + * + * Date.create().millisecondsUntil('1 hour from now') -> 3,600,000 + * Date.create().daysUntil('1 week from now') -> 7 + * Date.create().yearsUntil('15 years from now') -> 15 + * Date.create('15 years from now').yearsFromNow() -> 15 + * + ***/ + millisecondsUntil(date?: Date, locale?: string): number; + millisecondsUntil(date: string, locale?: string): number; + secondsUntil(date?: Date, locale?: string): number; + secondsUntil(date: string, locale?: string): number; + minutesUntil(date?: Date, locale?: string): number; + minutesUntil(date: string, locale?: string): number; + hoursUntil(date?: Date, locale?: string): number; + hoursUntil(date: string, locale?: string): number; + daysUntil(date?: Date, locale?: string): number; + daysUntil(date: string, locale?: string): number; + weeksUntil(date?: Date, locale?: string): number; + weeksUntil(date: string, locale?: string): number; + monthsUntil(date?: Date, locale?: string): number; + monthsUntil(date: string, locale?: string): number; + yearsUntil(date?: Date, locale?: string): number; + yearsUntil(date: string, locale?: string): number; + + /*** + * Sets the internal utc flag for the date. When on, UTC-based methods + * will be called internally. + * @method utc([on] = true) + * @returns Date + * @extra For more see @date_format. + * @example + * + * new Date().utc(true) + * new Date().utc(false) + * + ***/ + utc(on?: bool): Date; +} + +/*** +* @package DateRange +* @dependency date +* @description Date Ranges define a range of time. They can enumerate over specific points +* within that range, and be manipulated and compared. +* +***/ +interface DateRange { + start: Date; + end: Date; + + /*** + * Returns true if is contained inside the DateRange. + * may be a date or another DateRange. + * @method contains() + * @returns Boolean + * @example + * + * Date.range('2003', '2005').contains(Date.create('2004')) -> true + * + ***/ + contains(d: Date): bool; + contains(d: DateRange): bool; + + /*** + * Return the duration of the DateRange in milliseconds. + * @method duration() + * @returns Number + * @example + * + * Date.range('2003', '2005').duration() -> 94694400000 + * + ***/ + duration(): number; + + /*** + * Increments through the date range for each [unit], calling [fn] if it is passed. + * Returns an array of each increment visited. + * @method each[Unit]([fn]) + * @returns Date + * + * @set + * eachMillisecond + * eachSecond + * eachMinute + * eachHour + * eachDay + * eachWeek + * eachMonth + * eachYear + * + * @example + * + * Date.range('2003-01', '2003-02').eachMonth() -> [...] + * Date.range('2003-01-15', '2003-01-16').eachDay() -> [...] + * + ***/ + eachMillisecond(fn?: (d: Date) => void ): Date[]; + eachSecond(fn?: (d: Date) => void ): Date[]; + eachMinute(fn?: (d: Date) => void ): Date[]; + eachHour(fn?: (d: Date) => void ): Date[]; + eachDay(fn?: (d: Date) => void ): Date[]; + eachWeek(fn?: (d: Date) => void ): Date[]; + eachMonth(fn?: (d: Date) => void ): Date[]; + eachYear(fn?: (d: Date) => void ): Date[]; + + /*** + * Iterates through the DateRange for every , + * calling [fn] if it is passed. Returns an array of each increment visited. + * @method every(, [fn]) + * @returns Array + * @extra When is a number, increments will be to the exact millisecond. + * can also be a string in the format %{number} {unit}s%, in which + * case it will increment in the unit specified. Note that a discrepancy exists + * in the case of months, as %(2).months()% is an approximation. Stepping + * through the actual months by passing %"2 months"% is usually preferable in + * this case. + * @example + * + * Date.range('2003-01', '2003-03').every("2 months") -> [...] + * + ***/ + every(ms: number, fn?: (d: Date) => void ): Date[]; + every(increment: string, fn?: (d: Date) => void ): Date[]; + + /*** + * Returns a new DateRange with the latest starting point as its start, and the + * earliest ending point as its end. If the two ranges do not intersect this will + * effectively produce an invalid range. + * @method intersect() + * @returns DateRange + * @example + * + * Date.range('2003-01', '2005-01').intersect(Date.range('2004-01', '2006-01')) -> Jan 1, 2004..Jan 1, 2005 + * + ***/ + intersect(range: DateRange): DateRange; + + /*** + * Returns true if the DateRange is valid, false otherwise. + * @method isValid() + * @returns Boolean + * @example + * + * Date.range('2003', '2005').isValid() -> true + * Date.range('2005', '2003').isValid() -> false + * + ***/ + isValid(): bool; + + /*** + * Returns a string representation of the DateRange. + * @method toString() + * @returns String + * @example + * + * Date.range('2003', '2005').toString() -> January 1, 2003..January 1, 2005 + * + ***/ + toString(): string; + + /*** + * Returns a new DateRange with the earliest starting point as its start, + * and the latest ending point as its end. If the two ranges do not intersect + * this will effectively remove the "gap" between them. + * @method union() + * @returns DateRange + * @example + * + * Date.range('2003=01', '2005-01').union(Date.range('2004-01', '2006-01')) -> Jan 1, 2003..Jan 1, 2006 + * + ***/ + union(range: DateRange): DateRange; +} diff --git a/underscore/underscore-typed-1.4.2.d.ts b/underscore/underscore-typed-1.4.2.d.ts new file mode 100644 index 0000000000..510176117e --- /dev/null +++ b/underscore/underscore-typed-1.4.2.d.ts @@ -0,0 +1,2008 @@ +/* +underscore-1.4.2.d.ts may be freely distributed under the MIT license. + +Copyright (c) 2012 Josh Baldwin https://github.com/jbaldwin/underscore.d.ts + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*/ + +interface Underscore { + + /************** + * Collections * + **************/ + + /** + * 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, object). Delegates to the native forEach function if it exists. + * @param list Iterates over this list of elements. + * @param iterator Iterator function for each element `list`. + * @param context 'this' object in `iterator`, optional. + **/ + each( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * 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, object). Delegates to the native forEach function if it exists. + * @param obj Iterators over this object's properties. + * @param iterator Iterator function for each property on `obj`. + * @param context `this` object in the `iterator`, optional. + **/ + each( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * Alias for 'each'. + * @see each + **/ + forEach( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * Alias for 'each'. + * @see each + **/ + forEach( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * 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, object). + * @param list Maps the elements of this array. + * @param iterator Map iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The mapped array result. + **/ + map( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * 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, object). + * @param list Maps the properties of this object. + * @param iterator Map iterator function for each property on `obj`. + * @param context `this` object in `iterator`, optional. + * @return The mapped object result. + **/ + map( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * Alias for 'map'. + * @see map + **/ + collect( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Alias for 'map'. + * @see map + **/ + collect( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * 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. The iterator is passed four arguments: the memo, then the value + * and index (or key) of the iteration, and finally a reference to the entire list. + * @param list Reduces the elements of this array. + * @param iterator Reduce iterator function for each element in `list`. + * @param memo Initial reduce state. + * @param context `this` object in `iterator`, optional. + * @return Reduced object result. + **/ + reduce( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + inject( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + foldl( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * 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. + * @param list Reduces the elements of this array. + * @param iterator Reduce iterator function for each element in `list`. + * @param memo Initial reduce state. + * @param context `this` object in `iterator`, optional. + * @return Reduced object result. + **/ + reduceRight( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduceRight'. + * @see reduceRight + **/ + foldr( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * 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. + * @param list Searches for a value in this list. + * @param iterator Search iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The first acceptable found element in `list`, if nothing is found undefined/null is returned. + **/ + find( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + /** + * Alias for 'find'. + * @see find + **/ + detect( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + + /** + * 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. + * @param list Filter elements out of this list. + * @param iterator Filter iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The filtered list of elements. + **/ + filter( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Alias for 'filter'. + * @see filter + **/ + select( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Looks through each value in the list, returning an array of all the values that contain all + * of the key-value pairs listed in properties. + * @param list List to match elements again `properties`. + * @param properties The properties to check for on each element within `list`. + * @return The elements within `list` that contain the required `properties`. + **/ + where(list: any[], properties: any): any[]; + + /** + * Returns the values in list without the elements that the truth test (iterator) passes. + * The opposite of filter. + * Return all the elements for which a truth test fails. + * @param list Reject elements within this list. + * @param iterator Reject iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The rejected list of elements. + **/ + reject( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Returns true if all of the values in the list pass the iterator truth test. Delegates to the + * native method every, if present. + * @param list Truth test against all elements within this list. + * @param iterator Trust test iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return True if all elements passed the truth test, otherwise false. + **/ + all( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'all'. + * @see all + **/ + every( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * 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. + * @param list Truth test against all elements within this list. + * @param iterator Trust test iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return True if any elements passed the truth test, otherwise false. + **/ + any( + list: any[], + iterator?: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'any'. + * @see any + **/ + some( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Returns true if the value is present in the list. Uses indexOf internally, + * if list is an Array. + * @param list Checks each element to see if `value` is present. + * @param value The value to check for within `list`. + * @return True if `value` is present in `list`, otherwise false. + **/ + contains(list: any[], value: any): bool; + + /** + * Alias for 'contains'. + * @see contains + **/ + include(list: any[], value: any): bool; + + /** + * 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. + * @param list The element's in this list will each have the method `methodName` invoked. + * @param methodName The method's name to call on each element within `list`. + * @param arguments Additional arguments to pass to the method `methodName`. + **/ + invoke(list: any[], methodName: string, ...arguments: any[]): void; + + /** + * A convenient version of what is perhaps the most common use-case for map: extracting a list of + * property values. + * @param list The list to pluck elements out of that have the property `propertyName`. + * @param propertyName The property to look for on each element within `list`. + * @return The list of elements within `list` that have the property `propertyName`. + **/ + pluck(list: any[], propertyName: string): any[]; + + /** + * Returns the maximum value in list. + * @param list Finds the maximum value in this list. + * @return Maximum value in `list`. + **/ + max(list: number[]): number; + /** + * 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. + * @param list Finds the maximum value in this list. + * @param iterator Compares each element in `list` to find the maximum value. + * @param context `this` object in `iterator`, optional. + * @return The maximum element within `list`. + **/ + max( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Returns the minimum value in list. + * @param list Finds the minimum value in this list. + * @return Minimum value in `list`. + **/ + min(list: number[]): number; + /** + * 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. + * @param list Finds the minimum value in this list. + * @param iterator Compares each element in `list` to find the minimum value. + * @param context `this` object in `iterator`, optional. + * @return The minimum element within `list`. + **/ + min( + list: any[], + iterator: (obj: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Returns a sorted copy of list, ranked in ascending order by the results of running each value + * through iterator. Iterator may also be the string name of the property to sort by (eg. length). + * @param list Sorts this list. + * @param iterator Sort iterator for each element within `list`. + * @param context `this` object in `iterator`, optional. + * @return A sorted copy of `list`. + **/ + sortBy( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => number, + context?: any): any[]; + /** + * Returns a sorted copy of list, ranked in ascending order by the results of running each value + * through iterator. Iterator may also be the string name of the property to sort by (eg. length). + * @param list Sorts this list. + * @param iterator Sort iterator for each element within `list`. + * @param context `this` object in `iterator`, optional. + * @return A sorted copy of `list`. + **/ + sortBy( + list: any[], + iterator: string, + context?: any): any[]; + + /** + * Splits a collection into sets, grouped by the result of running each value through iterator. + * If iterator is a string instead of a function, groups by the property named by iterator on + * each of the values. + * @param list Groups this list. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the grouped elements from `list`. + **/ + groupBy( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: any[]; }; + /** + * Splits a collection into sets, grouped by the result of running each value through iterator. + * If iterator is a string instead of a function, groups by the property named by iterator on + * each of the values. + * @param list Groups this list. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the grouped elements from `list`. + **/ + groupBy( + list: any[], + iterator: string, + context?: any): { [key: string]: any[]; }; + + /** + * Sorts a list into groups and returns a count for the number of objects in each group. Similar + * to groupBy, but instead of returning a list of values, returns a count for the number of values + * in that group. + * @param list Group elements in this list and then count the number of elements in each group. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the number of elements in that group. + **/ + countBy( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: number; }; + /** + * Sorts a list into groups and returns a count for the number of objects in each group. Similar + * to groupBy, but instead of returning a list of values, returns a count for the number of values + * in that group. + * @param list Group elements in this list and then count the number of elements in each group. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the number of elements in that group. + **/ + countBy( + list: any[], + iterator: string, + context?: any): { [key: string]: number; }; + + /** + * Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle. + * @param list List to shuffle. + * @return Shuffled copy of `list`. + **/ + shuffle(list: any[]): any[]; + + /** + * Converts the list (anything that can be iterated over), into a real Array. Useful for transmuting + * the arguments object. + * @param list object to transform into an array. + * @return `list` as an array. + **/ + toArray(list: any): any[]; + + /** + * Return the number of values in the list. + * @param list Count the number of values/elements in this list. + * @return Number of values in `list`. + **/ + size(list: any): number; + + /********* + * Arrays * + **********/ + + /** + * Returns the first element of an array. Passing n will return the first n elements of the array. + * @param array Retrieves the first element of this array. + * @return Returns the first element of `array`. + **/ + first(array: any[]): any; + /** + * Returns the first element of an array. Passing n will return the first n elements of the array. + * @param array Retreives the first `n` elements of this array. + * @param n Return more than one element from `array`. + * @return Returns the first `n` elements from `array. + **/ + first(array: any[], n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + head(array: any[]): any; + /** + * Alias for 'first'. + * @see first + **/ + head(array: any[], n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + take(array: any[]): any; + /** + * Alias for 'first'. + * @see first + **/ + take(array: any[], n: number): any[]; + + /** + * Returns everything but the last entry of the array. Especially useful on the arguments object. + * Pass n to exclude the last n elements from the result. + * @param array Retreive all elements except the last `n`. + * @param n Leaves this many elements behind, optional. + * @return Returns everything but the last `n` elements of `array`. + **/ + initial(array: any[], n?: number): any[]; + + /** + * Returns the last element of an array. Passing n will return the last n elements of the array. + * @param array Retrieves the last element of this array. + * @return Returns the last element of `array`. + **/ + last(array: any[]): any; + /** + * Returns the last element of an array. Passing n will return the last n elements of the array. + * @param array Retreives the last `n` elements of this array. + * @param n Return more than one element from `array`. + * @return Returns the last `n` elements from `array. + **/ + last(array: any[], n: number): any[]; + + /** + * Returns the rest of the elements in an array. Pass an index to return the values of the array + * from that index onward. + * @param array The array to retrieve all but the first `index` elements. + * @param index The index to start retrieving elements forward from, optional, default = 1. + * @return Returns the elements of `array` from `index` to the end of `array`. + **/ + rest(array: any[], index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + tail(array: any[], index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + drop(array: any[], index?: number): any[]; + + /** + * Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", + * undefined and NaN are all falsy. + * @param array Array to compact. + * @return Copy of `array` without false values. + **/ + compact(array: any[]): any[]; + + /** + * Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will + * only be flattened a single level. + * @param array The array to flatten. + * @param shallow If true then only flatten one level, optional, default = false. + * @return `array` flattened. + **/ + flatten(array: any, shallow?: bool): any; + + /** + * Returns a copy of the array with all instances of the values removed. + * @param array The array to remove `values` from. + * @param values The values to remove from `array`. + * @return Copy of `array` without `values`. + **/ + without(array: any[], ...values: any[]): any[]; + + /** + * Computes the union of the passed-in arrays: the list of unique items, in order, that are + * present in one or more of the arrays. + * @param arrays Array of arrays to compute the union of. + * @return The union of elements within `arrays`. + **/ + union(...arrays: any[][]): any[]; + + /** + * 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. + * @param arrays Array of arrays to compute the intersection of. + * @return The intersection of elements within `arrays`. + **/ + intersection(...arrays: any[][]): any[]; + + /** + * Similar to without, but returns the values from array that are not present in the other arrays. + * @param array Keeps values that are within `others`. + * @param others The values to keep within `array`. + * @return Copy of `array` with only `others` values. + **/ + difference(array: any[], ...others: any[]): any[]; + + /** + * 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. If + * you want to compute unique items based on a transformation, pass an iterator function. + * @param array Array to remove duplicates from. + * @param isSorted True if `array` is already sorted, optiona, default = false. + * @param iterator Transform the elements of `array` before comparisons for uniqueness. + * @return Copy of `array` where all elements are unique. + **/ + uniq( + array: any[], + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any): any[]; + + /** + * Alias for 'uniq'. + * @see uniq + **/ + unique(array: any[], + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any): any[]; + + /** + * 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. + * If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion. + * @param arrays The arrays to merge/zip. + * @return Zipped version of `arrays`. + **/ + zip(...arrays: any[][]): any[][]; + + /** + * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a + * list of keys, and a list of values. + * @param keys Key array. + * @param values Value array. + * @return An object containing the `keys` as properties and `values` as the property values. + **/ + object(keys: string[], values: any[]): any; + /** + * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a + * list of keys, and a list of values. + * @param keyValuePairs Array of [key, value] pairs. + * @return An object containing the `keys` as properties and `values` as the property values. + **/ + object(...keyValuePairs: any[][]): any; + + /** + * 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 ... or, pass a number + * as the third argument in order to look for the first matching value in the array after the given index. + * @param array The array to search for the index of `value`. + * @param value The value to search for within `array`. + * @param isSorted True if the array is already sorted, optional, default = false. + * @return The index of `value` within `array`. + **/ + indexOf(array: any[], value: any, isSorted?: bool): number; + + /** + * 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. Pass fromIndex to start your search at a given index. + * @param array The array to search for the last index of `value`. + * @param value The value to search for within `array`. + * @param from The starting index for the search, optional. + * @return The index of the last occurance of `value` within `array`. + **/ + lastIndexOf(array: any[], value: any, from?: number): number; + + /** + * 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, including the value you pass. + * @param list The sorted list. + * @param value The value to determine its index within `list`. + * @param iterator Iterator to compute the sort ranking of each value, optional. + * @return The index where `value` should be inserted into `list`. + **/ + sortedIndex(list: any[], value: any, iterator?: (element: any) => number): number; + + /** + * 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. + * @param start Start here. + * @param stop Stop here. + * @param step The number to count up by each iteration, optional, default = 1. + * @return Array of numbers from `start` to `stop` with increments of `step`. + **/ + range(start: number, stop: number, step?: number): number[]; + /** + * 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. + * @param stop Stop here. + * @return Array of numbers from 0 to `stop` with increments of 1. + * @note If start is not specified the implementation will never pull the step (step = arguments[2] || 0) + **/ + range(stop: number): number[]; + + /************ + * Functions * + *************/ + + /** + * 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 partial application. + * @param fn The function to bind `this` to `object`. + * @param object The `this` pointer whenever `fn` is called. + * @param arguments Additional arguments to pass to `fn` when called. + * @return `fn` with `this` bound to `object`. + **/ + bind(fn: Function, object: any, ...arguments: any[]): Function; + + + /** + * 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. + * @param object The object to bind the methods `methodName` to. + * @param methodNames The methods to bind to `object`, optional and if not provided all of `object`'s + * methods are bound. + **/ + bindAll(object: any, ...methodNames: string[]): void; + + /** + * 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. The default hashFunction just uses the first argument to the + * memoized function as the key. + * @param fn Computationally expensive function that will now memoized results. + * @param hashFn Hash function for storing the result of `fn`. + * @return Memoized version of `fn`. + **/ + memoize(fn: Function, hashFn?: (n: any) => string): Function; + + /** + * 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. + * @param fn Function to delay `waitMS` amount of ms. + * @param waitMS The amount of milliseconds to delay `fn`. + * @arguments Additional arguments to pass to `fn`. + **/ + delay(fn: Function, waitMS: number, ...arguments: any[]): void; + + /** + * 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. If you pass the optional arguments, they will be forwarded on + * to the function when it is invoked. + * @param fn The function to defer. + * @param arguments Additional arguments to pass to `fn`. + **/ + defer(fn: Function, ...arguments: any[]): void; + + /** + * Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, + * will only actually call the original function at most once per every wait milliseconds. Useful for + * rate-limiting events that occur faster than you can keep up with. + * @param fn Function to throttle `waitMS` ms. + * @param waitMS The number of milliseconds to wait before `fn` can be invoked again. + * @return `fn` with a throttle of `waitMS`. + **/ + throttle(fn: Function, waitMS: number): Function; + + /** + * Creates and returns a new debounced version of the passed function that will postpone its execution + * until after wait milliseconds have elapsed since the last time it was invoked. 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, and so on. + * + * Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead + * of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double + *-clicks on a "submit" button from firing a second time. + * @param fn Function to debounce `waitMS` ms. + * @param waitMS The number of milliseconds to wait before `fn` can be invoked again. + * @param immediate True if `fn` should be invoked on the leading edge of `waitMS` instead of the trailing edge. + * @return Debounced version of `fn` that waits `waitMS` ms when invoked. + **/ + debounce(fn: Function, waitMS: number, immediate?: bool): Function; + + /** + * Creates a version of the function that can only be called one time. Repeated calls to the modified + * function will have no effect, returning the value from the original call. Useful for initialization + * functions, instead of having to set a boolean flag and then check it later. + * @param fn Function to only execute once. + * @return Copy of `fn` that can only be invoked once. + **/ + once(fn: Function): Function; + + /** + * Creates a version of the function that will only be run after first being called count times. Useful + * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, + * before proceeding. + * @param count Number of times to be called before actually executing. + * @fn The function to defer execution `count` times. + * @return Copy of `fn` that will not execute until it is invoked `count` times. + **/ + after(count: number, fn: Function): Function; + + /** + * 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. + * @param fn Function to wrap. + * @param wrapper The function that will wrap `fn`. + * @return Wrapped version of `fn. + **/ + wrap(fn: Function, wrapper: (fn: Function, ...args: any[]) => any): Function; + + /** + * 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())). + * @param functions List of functions to compose. + * @return Composition of `functions`. + **/ + compose(...functions: Function[]): Function; + + /********** + * Objects * + ***********/ + + /** + * Retrieve all the names of the object's properties. + * @param object Retreive the key or property names from this object. + * @return List of all the property names on `object`. + **/ + keys(object: any): string[]; + + /** + * Return all of the values of the object's properties. + * @param object Retreive the values of all the properties on this object. + * @return List of all the values on `object`. + **/ + values(object: any): any[]; + + /** + * Convert an object into a list of [key, value] pairs. + * @param object Convert this object to a list of [key, value] pairs. + * @return List of [key, value] pairs on `object`. + **/ + pairs(object: any): any[][]; + + /** + * Returns a copy of the object where the keys have become the values and the values the keys. + * For this to work, all of your object's values should be unique and string serializable. + * @param object Object to invert key/value pairs. + * @return An inverted key/value paired version of `object`. + **/ + invert(object: any): any; + + /** + * 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. + * @param object Object to pluck all function property names from. + * @return List of all the function names on `object`. + **/ + functions(object: any): string[]; + + /** + * Copy all of the properties in the source objects over to the destination object, and return + * the destination object. It's in-order, so the last source will override properties of the + * same name in previous arguments. + * @param destination Object to extend all the properties from `sources`. + * @param sources Extends `destination` with all properties from these source objects. + * @return `destination` extended with all the properties from the `sources` objects. + **/ + extend(destination: any, ...sources: any[]): any; + + /** + * Return a copy of the object, filtered to only have values for the whitelisted keys + * (or array of valid keys). + * @param object Object to strip unwanted key/value pairs. + * @keys The key/value pairs to keep on `object`. + * @return Copy of `object` with only the `keys` properties. + **/ + pick(object: any, ...keys: string[]): any; + + /** + * Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). + * @param object Object to strip unwanted key/value pairs. + * @param keys The key/value pairs to remove on `object`. + * @return Copy of `object` without the `keys` properties. + **/ + omit(object: any, ...keys: string[]): any; + + /** + * Fill in null and undefined properties in object with values from the defaults objects, + * and return the object. As soon as the property is filled, further defaults will have no effect. + * @param object Fill this object with default values. + * @param defaults The default values to add to `object`. + * @return `object` with added `defaults` values. + **/ + defaults(object: any, ...defaults: any[]): any; + + /** + * Create a shallow-copied clone of the object. + * Any nested objects or arrays will be copied by reference, not duplicated. + * @param object Object to clone. + * @return Copy of `object`. + **/ + clone(object: any): any; + /** + * Create a shallow-copied clone of the object. + * Any nested objects or arrays will be copied by reference, not duplicated. + * @param list List to clone. + * @return Copy of `list`. + **/ + clone(list: any[]): any[]; + + /** + * 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. + * @param object Argument to `interceptor`. + * @param intercepter The function to modify `object` before continuing the method chain. + * @return Modified `object`. + **/ + tap(object: any, intercepter: Function): any; + + /** + * Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe + * reference to the hasOwnProperty function, in case it's been overridden accidentally. + * @param object Object to check for `key`. + * @param key The key to check for on `object`. + * @return True if `key` is a property on `object`, otherwise false. + **/ + has(object: any, key: string): bool; + + /** + * Performs an optimized deep comparison between the two objects, + * to determine if they should be considered equal. + * @param object Compare to `other`. + * @param other Compare to `object`. + * @return True if `object` is equal to `other`. + **/ + isEqual(object: any, other: any): bool; + + /** + * Returns true if object contains no values. + * @param object Check if this object has no properties or values. + * @return True if `object` is empty. + **/ + isEmpty(object: any): bool; + /** + * Returns true if the list contains no values. + * @param object Check if this list has no elements. + * @return True if `list` is empty. + **/ + isEmpty(list: any[]): bool; + + /** + * Returns true if object is a DOM element. + * @param object Check if this object is a DOM element. + * @return True if `object` is a DOM element, otherwise false. + **/ + isElement(object: any): bool; + + /** + * Returns true if object is an Array. + * @param object Check if this object is an Array. + * @return True if `object` is an Array, otherwise false. + **/ + isArray(object: any): bool; + + /** + * Returns true if value is an Object. Note that JavaScript arrays and functions are objects, + * while (normal) strings and numbers are not. + * @param object Check if this object is an Object. + * @return True of `object` is an Object, otherwise false. + **/ + isObject(object: any): bool; + + /** + * Returns true if object is an Arguments object. + * @param object Check if this object is an Arguments object. + * @return True if `object` is an Arguments object, otherwise false. + **/ + isArguments(object: any): bool; + + /** + * Returns true if object is a Function. + * @param object Check if this object is a Function. + * @return True if `object` is a Function, otherwise false. + **/ + isFunction(object: any): bool; + + /** + * Returns true if object is a String. + * @param object Check if this object is a String. + * @return True if `object` is a String, otherwise false. + **/ + isString(object: any): bool; + + /** + * Returns true if object is a Number (including NaN). + * @param object Check if this object is a Number. + * @return True if `object` is a Number, otherwise false. + **/ + isNumber(object: any): bool; + + /** + * Returns true if object is a finite Number. + * @param object Check if this object is a finite Number. + * @return True if `object` is a finite Number. + **/ + isFinite(object: any): bool; + + /** + * Returns true if object is either true or false. + * @param object Check if this object is a bool. + * @return True if `object` is a bool, otherwise false. + **/ + isBoolean(object: any): bool; + + /** + * Returns true if object is a Date. + * @param object Check if this object is a Date. + * @return True if `object` is a Date, otherwise false. + **/ + isDate(object: any): bool; + + /** + * Returns true if object is a RegExp. + * @param object Check if this object is a RegExp. + * @return True if `object` is a RegExp, otherwise false. + **/ + isRegExp(object: any): bool; + + /** + * 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. + * @param object Check if this object is NaN. + * @return True if `object` is NaN, otherwise false. + **/ + isNaN(object: any): bool; + + /** + * Returns true if the value of object is null. + * @param object Check if this object is null. + * @return True if `object` is null, otherwise false. + **/ + isNull(object: any): bool; + + /** + * Returns true if value is undefined. + * @param object Check if this object is undefined. + * @return True if `object` is undefined, otherwise false. + **/ + isUndefined(object: any): bool; + + /********** + * Utility * + ***********/ + + /** + * Give control of the "_" variable back to its previous owner. + * Returns a reference to the Underscore object. + * @return Underscore object reference. + **/ + noConflict(): Underscore; + + /** + * 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. + * @param value Identity of this object. + * @return `value`. + **/ + identity(value: any): any; + + /** + * Invokes the given iterator function n times. + * Each invocation of iterator is called with an index argument + * @param n Number of times to invoke `iterator`. + * @param iterator Function iterator to invoke `n` times. + * @param context `this` object in `iterator`, optional. + **/ + times(n: number, iterator: (n: number) => void , context?: any): void; + + /** + * Returns a random integer between min and max, inclusive. If you only pass one argument, + * it will return a number between 0 and that number. + * @param max The maximum random number. + * @return A random number between 0 and `max`. + **/ + random(max: number): number; + /** + * Returns a random integer between min and max, inclusive. If you only pass one argument, + * it will return a number between 0 and that number. + * @param min The minimum random number. + * @param max The maximum random number. + * @return A random number between `min` and `max`. + **/ + random(min: number, max: number): number; + + /** + * 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. + * @param object Mixin object containing key/function pairs to add to the Underscore object. + **/ + mixin(object: any): void; + + /** + * 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. Without prefix, returns an integer. + * @return Unique number ID. + **/ + uniqueId(): number; + /** + * 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. Without prefix, returns an integer. + * @param prefix A prefix string to start the unique ID with. + * @return Unique string ID beginning with `prefix`. + **/ + uniqueId(prefix: string): string; + + /** + * Escapes a string for insertion into HTML, replacing &, <, >, ", ', and / characters. + * @param str Raw string to escape. + * @return `str` HTML escaped. + **/ + escape(str: string): string; + + /** + * If the value of the named property is a function then invoke it; otherwise, return it. + * @param object Object to maybe invoke function `property` on. + * @param property The function by name to invoke on `object`. + * @return The result of invoking the function `property` on `object. + **/ + result(object: any, property: string): any; + + /** + * 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 + * <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %> When + * you evaluate a template function, pass in a data object that has properties corresponding to + * the template's free variables. If you're writing a one-off, you can pass the data object as + * the second parameter to template in order to render immediately instead of returning a template + * function. The settings argument should be a hash containing any _.templateSettings that should + * be overridden. + * @param templateString Underscore HTML template. + * @param data Data to use when compiling `templateString`. + * @param settings Settings to use while compiling. + * @return Returns the compiled Underscore HTML template. + **/ + template(templateString: string, data?: any, settings?: UnderscoreTemplateSettings): any; + + /** + * By default, Underscore uses ERB-style template delimiters, change the + * following template settings to use alternative delimiters. + **/ + templateSettings: UnderscoreTemplateSettings; + + /*********** + * Chaining * + ************/ + + /** + * Returns a wrapped object. Calling methods on this object will continue to return wrapped objects + * until value() is used. + * @param obj Object to chain. + * @return Wrapped `obj`. + **/ + chain(obj: any): any; + + /** + * Extracts the value of a wrapped object. + * @param obj Wrapped object to extract the value from. + * @return Value of `obj`. + **/ + value(obj: any): any; + + /************** + * OOP Wrapper * + **************/ + + /** + * Underscore OOP Wrapper, all Underscore functions that take an object + * as the first parameter can be invoked through this function. + * @param key First argument to Underscore object functions. + **/ + (obj: any): UnderscoreOOPWrapper; +} + +/** +* underscore.js template settings, set templateSettings or pass as an argument +* to 'template()' to overide defaults. +**/ +interface UnderscoreTemplateSettings { + /** + * Default value is '/<%([\s\S]+?)%>/g'. + **/ + evaluate?: RegExp; + + /** + * Default value is '/<%=([\s\S]+?)%>/g'. + **/ + interpolate?: RegExp; + + /** + * Default value is '/<%-([\s\S]+?)%>/g'. + **/ + escape?: RegExp; +} + +interface UnderscoreOOPWrapper { + + /************** + * Collections * + **************/ + + /** + * Wrapped type `any[]`. + * @see _.each + **/ + each( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * Wrapped type `object`. + * @see _.each + **/ + each( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * Alias for 'each'. + * @see each + **/ + forEach( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * Alias for 'each'. + * @see each + **/ + forEach( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Wrapped type `object`. + * @see _.map + **/ + map( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * Alias for 'map'. + * @see map + **/ + collect( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Alias for 'map'. + * @see map + **/ + collect( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.reduce + **/ + reduce( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + inject( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + foldl( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Wrapped type `any[]`. + * @see _.reduceRight + **/ + reduceRight( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduceRight'. + * @see reduceRight + **/ + foldr( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Wrapped type `any[]`. + * @see _.find + **/ + find( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + /** + * Alias for 'find'. + * @see find + **/ + detect( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + + /** + * Wrapped type `any[]`. + * @see _.filter + **/ + filter( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Alias for 'filter'. + * @see filter + **/ + select( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.where + **/ + where(list: any[], properties: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.reject + **/ + reject( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.all + **/ + all( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'all'. + * @see all + **/ + every( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Wrapped type `any[]`. + * @see _.any + **/ + any( + list: any[], + iterator?: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'any'. + * @see any + **/ + some( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Wrapped type `any[]`. + * @see _.contains + **/ + contains(value: any): bool; + + /** + * Alias for 'contains'. + * @see contains + **/ + include(value: any): bool; + + /** + * Wrapped type `any[]`. + * @see _.invoke + **/ + invoke(methodName: string, ...arguments: any[]): void; + + /** + * Wrapped type `any[]`. + * @see _.pluck + **/ + pluck(propertyName: string): any[]; + + /** + * Wrapped type `number[]`. + * @see _.max + **/ + max(): number; + /** + * Wrapped type `any[]`. + * @see _.max + **/ + max( + iterator: (element: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Wrapped type `number[]`. + * @see _.min + **/ + min(): number; + /** + * Wrapped type `any[]`. + * @see _.min + **/ + min( + iterator: (obj: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Wrapped type `any[]`. + * @see _.sortBy + **/ + sortBy( + iterator: (element: any, index?: number, list?: any[]) => number, + context?: any): any[]; + /** + * Wrapped type `any[]`. + * @see _.sortBy + **/ + sortBy( + iterator: string, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.groupBy + **/ + groupBy( + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: any[]; }; + /** + * Wrapped type `any[]`. + * @see _.groupBy + **/ + groupBy( + iterator: string, + context?: any): { [key: string]: any[]; }; + + /** + * Wrapped type `any[]`. + * @see _.countBy + **/ + countBy( + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: number; }; + /** + * Wrapped type `any[]`. + * @see _.countBy + **/ + countBy( + iterator: string, + context?: any): { [key: string]: number; }; + + /** + * Wrapped type `any[]`. + * @see _.shuffle + **/ + shuffle(): any[]; + + /** + * Wrapped type `any`. + * @see _.toArray + **/ + toArray(): any[]; + + /** + * Wrapped type `any`. + * @see _.size + **/ + size(): number; + + /********* + * Arrays * + **********/ + + /** + * Wrapped type `any[]`. + * @see _.first + **/ + first(): any; + /** + * Wrapped type `any[]`. + * @see _.first + **/ + first(n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + head(): any; + /** + * Alias for 'first'. + * @see first + **/ + head(n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + take(): any; + /** + * Alias for 'first'. + * @see first + **/ + take(n: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.initial + **/ + initial(n?: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.last + **/ + last(): any; + /** + * Wrapped type `any[]`. + * @see _.last + **/ + last(n: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.rest + **/ + rest(index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + tail(index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + drop(index?: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.compact + **/ + compact(): any[]; + + /** + * Wrapped type `any`. + * @see _.flatten + **/ + flatten(shallow?: bool): any; + + /** + * Wrapped type `any[]`. + * @see _.without + **/ + without(...values: any[]): any[]; + + /** + * Wrapped type `any[][]`. + * @see _.union + **/ + union(...arrays: any[][]): any[]; + + /** + * Wrapped type `any[][]`. + * @see _.intersection + **/ + intersection(...arrays: any[][]): any[]; + + /** + * Wrapped type `any[]`. + * @see _.difference + **/ + difference(...others: any[]): any[]; + + /** + * Wrapped type `any[]`. + * @see _.uniq + **/ + uniq( + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any): any[]; + + /** + * Alias for 'uniq'. + * @see uniq + **/ + unique( + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any): any[]; + + /** + * Wrapped type `any[][]`. + * @see _.zip + **/ + zip(...arrays: any[][]): any[][]; + + /** + * Wrapped type `any[][]`. + * @see _.object + **/ + object(...keyValuePairs: any[][]): any; + + /** + * Wrapped type `any[]`. + * @see _.indexOf + **/ + indexOf(value: any, isSorted?: bool): number; + + /** + * Wrapped type `any[]`. + * @see _.lastIndexOf + **/ + lastIndexOf(value: any, from?: number): number; + + /** + * Wrapped type `any[]`. + * @see _.sortedIndex + **/ + sortedIndex(value: any, iterator?: (element: any) => number): number; + + /** + * Wrapped type `number`. + * @see _.range + **/ + range(stop: number, step?: number): number[]; + /** + * Wrapped type `number`. + * @see _.range + **/ + range(): number[]; + + /************ + * Functions * + *************/ + + /** + * Wrapped type `Function`. + * @see _.bind + **/ + bind(object: any, ...arguments: any[]): Function; + + + /** + * Wrapped type `object`. + * @see _.bindAll + **/ + bindAll(...methodNames: string[]): void; + + /** + * Wrapped type `Function`. + * @see _.memoize + **/ + memoize(hashFn?: (n: any) => string): Function; + + /** + * Wrapped type `Function`. + * @see _.delay + **/ + delay(waitMS: number, ...arguments: any[]): void; + + /** + * Wrapped type `Function`. + * @see _.defer + **/ + defer(...arguments: any[]): void; + + /** + * Wrapped type `Function`. + * @see _.throttle + **/ + throttle(waitMS: number): Function; + + /** + * Wrapped type `Function`. + * @see _.debounce + **/ + debounce(waitMS: number, immediate?: bool): Function; + + /** + * Wrapped type `Function`. + * @see _.once + **/ + once(): Function; + + /** + * Wrapped type `number`. + * @see _.after + **/ + after(fn: Function): Function; + + /** + * Wrapped type `Function`. + * @see _.wrap + **/ + wrap(wrapper: (fn: Function, ...args: any[]) => any): Function; + + /** + * Wrapped type `Function[]`. + * @see _.compose + **/ + compose(...functions: Function[]): Function; + + /********** + * Objects * + ***********/ + + /** + * Wrapped type `object`. + * @see _.keys + **/ + keys(): string[]; + + /** + * Wrapped type `object`. + * @see _.values + **/ + values(): any[]; + + /** + * Wrapped type `object`. + * @see _.pairs + **/ + pairs(): any[][]; + + /** + * Wrapped type `object`. + * @see _.invert + **/ + invert(): any; + + /** + * Wrapped type `object`. + * @see _.functions + **/ + functions(): string[]; + + /** + * Wrapped type `object`. + * @see _.extend + **/ + extend(...sources: any[]): any; + + /** + * Wrapped type `object`. + * @see _.pick + **/ + pick(...keys: string[]): any; + + /** + * Wrapped type `object`. + * @see _.omit + **/ + omit(...keys: string[]): any; + + /** + * Wrapped type `object`. + * @see _.defaults + **/ + defaults(...defaults: any[]): any; + + /** + * Wrapped type `object`. + * @see _.clone + **/ + clone(object: any): any; + /** + * Wrapped type `any[]`. + * @see _.clone + **/ + clone(list: any[]): any[]; + + /** + * Wrapped type `object`. + * @see _.tap + **/ + tap(intercepter: Function): any; + + /** + * Wrapped type `object`. + * @see _.has + **/ + has(key: string): bool; + + /** + * Wrapped type `object`. + * @see _.isEqual + **/ + isEqual(other: any): bool; + + /** + * Wrapped type `object`. + * @see _.isEmpty + **/ + isEmpty(object: any): bool; + /** + * Wrapped type `any[]`. + * @see _.isEmpty + **/ + isEmpty(list: any[]): bool; + + /** + * Wrapped type `object`. + * @see _.isElement + **/ + isElement(): bool; + + /** + * Wrapped type `object`. + * @see _.isArray + **/ + isArray(): bool; + + /** + * Wrapped type `object`. + * @see _.isObject + **/ + isObject(): bool; + + /** + * Wrapped type `object`. + * @see _.isArguments + **/ + isArguments(): bool; + + /** + * Wrapped type `object`. + * @see _.isFunction + **/ + isFunction(): bool; + + /** + * Wrapped type `object`. + * @see _.isString + **/ + isString(): bool; + + /** + * Wrapped type `object`. + * @see _.isNumber + **/ + isNumber(): bool; + + /** + * Wrapped type `object`. + * @see _.isFinite + **/ + isFinite(): bool; + + /** + * Wrapped type `object`. + * @see _.isBoolean + **/ + isBoolean(): bool; + + /** + * Wrapped type `object`. + * @see _.isDate + **/ + isDate(): bool; + + /** + * Wrapped type `object`. + * @see _.isRegExp + **/ + isRegExp(): bool; + + /** + * Wrapped type `object`. + * @see _.isNaN + **/ + isNaN(): bool; + + /** + * Wrapped type `object`. + * @see _.isNull + **/ + isNull(): bool; + + /** + * Wrapped type `object`. + * @see _.isUndefined + **/ + isUndefined(): bool; + + /********** + * Utility * + ***********/ + + /** + * Wrapped type `any`. + * @see _.identity + **/ + identity(): any; + + /** + * Wrapped type `number`. + * @see _.times + **/ + times(iterator: (n: number) => void , context?: any): void; + + /** + * Wrapped type `number`. + * @see _.random + **/ + random(): number; + /** + * Wrapped type `number`. + * @see _.random + **/ + random(max: number): number; + + /** + * Wrapped type `object`. + * @see _.mixin + **/ + mixin(): void; + + /** + * Wrapped type `string`. + * @see _.uniqueId + **/ + uniqueId(): string; + + /** + * Wrapped type `string`. + * @see _.escape + **/ + escape(): string; + + /** + * Wrapped type `object`. + * @see _.result + **/ + result(property: string): any; + + /** + * Wrapped type `string`. + * @see _.template + **/ + template(data?: any, settings?: UnderscoreTemplateSettings): any; + + /*********** + * Chaining * + ************/ + + /** + * Wrapped type `any`. + * @see _.chain + **/ + chain(): any; + + /** + * Wrapped type `any`. + * @see _.value + **/ + value(): any; +} + +declare var _: Underscore; diff --git a/underscore/underscore-typed-1.4.3.d.ts b/underscore/underscore-typed-1.4.3.d.ts new file mode 100644 index 0000000000..56fe7583ab --- /dev/null +++ b/underscore/underscore-typed-1.4.3.d.ts @@ -0,0 +1,2031 @@ +/* +underscore-1.4.3.d.ts may be freely distributed under the MIT license. + +Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/underscore.d.ts + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*/ + +interface Underscore { + + /************** + * Collections * + **************/ + + /** + * 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, object). Delegates to the native forEach function if it exists. + * @param list Iterates over this list of elements. + * @param iterator Iterator function for each element `list`. + * @param context 'this' object in `iterator`, optional. + **/ + each( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * 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, object). Delegates to the native forEach function if it exists. + * @param obj Iterators over this object's properties. + * @param iterator Iterator function for each property on `obj`. + * @param context `this` object in the `iterator`, optional. + **/ + each( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * Alias for 'each'. + * @see each + **/ + forEach( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * Alias for 'each'. + * @see each + **/ + forEach( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * 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, object). + * @param list Maps the elements of this array. + * @param iterator Map iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The mapped array result. + **/ + map( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * 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, object). + * @param list Maps the properties of this object. + * @param iterator Map iterator function for each property on `obj`. + * @param context `this` object in `iterator`, optional. + * @return The mapped object result. + **/ + map( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * Alias for 'map'. + * @see map + **/ + collect( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Alias for 'map'. + * @see map + **/ + collect( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * 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. The iterator is passed four arguments: the memo, then the value + * and index (or key) of the iteration, and finally a reference to the entire list. + * @param list Reduces the elements of this array. + * @param iterator Reduce iterator function for each element in `list`. + * @param memo Initial reduce state. + * @param context `this` object in `iterator`, optional. + * @return Reduced object result. + **/ + reduce( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + inject( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + foldl( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * 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. + * @param list Reduces the elements of this array. + * @param iterator Reduce iterator function for each element in `list`. + * @param memo Initial reduce state. + * @param context `this` object in `iterator`, optional. + * @return Reduced object result. + **/ + reduceRight( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduceRight'. + * @see reduceRight + **/ + foldr( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * 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. + * @param list Searches for a value in this list. + * @param iterator Search iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The first acceptable found element in `list`, if nothing is found undefined/null is returned. + **/ + find( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + /** + * Alias for 'find'. + * @see find + **/ + detect( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + + /** + * 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. + * @param list Filter elements out of this list. + * @param iterator Filter iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The filtered list of elements. + **/ + filter( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Alias for 'filter'. + * @see filter + **/ + select( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Looks through each value in the list, returning an array of all the values that contain all + * of the key-value pairs listed in properties. + * @param list List to match elements again `properties`. + * @param properties The properties to check for on each element within `list`. + * @return The elements within `list` that contain the required `properties`. + **/ + where(list: any[], properties: any): any[]; + + /** + * Returns the values in list without the elements that the truth test (iterator) passes. + * The opposite of filter. + * Return all the elements for which a truth test fails. + * @param list Reject elements within this list. + * @param iterator Reject iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The rejected list of elements. + **/ + reject( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Returns true if all of the values in the list pass the iterator truth test. Delegates to the + * native method every, if present. + * @param list Truth test against all elements within this list. + * @param iterator Trust test iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return True if all elements passed the truth test, otherwise false. + **/ + all( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'all'. + * @see all + **/ + every( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * 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. + * @param list Truth test against all elements within this list. + * @param iterator Trust test iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return True if any elements passed the truth test, otherwise false. + **/ + any( + list: any[], + iterator?: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'any'. + * @see any + **/ + some( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Returns true if the value is present in the list. Uses indexOf internally, + * if list is an Array. + * @param list Checks each element to see if `value` is present. + * @param value The value to check for within `list`. + * @return True if `value` is present in `list`, otherwise false. + **/ + contains(list: any[], value: any): bool; + + /** + * Alias for 'contains'. + * @see contains + **/ + include(list: any[], value: any): bool; + + /** + * 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. + * @param list The element's in this list will each have the method `methodName` invoked. + * @param methodName The method's name to call on each element within `list`. + * @param arguments Additional arguments to pass to the method `methodName`. + **/ + invoke(list: any[], methodName: string, ...arguments: any[]): void; + + /** + * A convenient version of what is perhaps the most common use-case for map: extracting a list of + * property values. + * @param list The list to pluck elements out of that have the property `propertyName`. + * @param propertyName The property to look for on each element within `list`. + * @return The list of elements within `list` that have the property `propertyName`. + **/ + pluck(list: any[], propertyName: string): any[]; + + /** + * Returns the maximum value in list. + * @param list Finds the maximum value in this list. + * @return Maximum value in `list`. + **/ + max(list: number[]): number; + /** + * 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. + * @param list Finds the maximum value in this list. + * @param iterator Compares each element in `list` to find the maximum value. + * @param context `this` object in `iterator`, optional. + * @return The maximum element within `list`. + **/ + max( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Returns the minimum value in list. + * @param list Finds the minimum value in this list. + * @return Minimum value in `list`. + **/ + min(list: number[]): number; + /** + * 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. + * @param list Finds the minimum value in this list. + * @param iterator Compares each element in `list` to find the minimum value. + * @param context `this` object in `iterator`, optional. + * @return The minimum element within `list`. + **/ + min( + list: any[], + iterator: (obj: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Returns a sorted copy of list, ranked in ascending order by the results of running each value + * through iterator. Iterator may also be the string name of the property to sort by (eg. length). + * @param list Sorts this list. + * @param iterator Sort iterator for each element within `list`. + * @param context `this` object in `iterator`, optional. + * @return A sorted copy of `list`. + **/ + sortBy( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => number, + context?: any): any[]; + /** + * Returns a sorted copy of list, ranked in ascending order by the results of running each value + * through iterator. Iterator may also be the string name of the property to sort by (eg. length). + * @param list Sorts this list. + * @param iterator Sort iterator for each element within `list`. + * @param context `this` object in `iterator`, optional. + * @return A sorted copy of `list`. + **/ + sortBy( + list: any[], + iterator: string, + context?: any): any[]; + + /** + * Splits a collection into sets, grouped by the result of running each value through iterator. + * If iterator is a string instead of a function, groups by the property named by iterator on + * each of the values. + * @param list Groups this list. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the grouped elements from `list`. + **/ + groupBy( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: any[]; }; + /** + * Splits a collection into sets, grouped by the result of running each value through iterator. + * If iterator is a string instead of a function, groups by the property named by iterator on + * each of the values. + * @param list Groups this list. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the grouped elements from `list`. + **/ + groupBy( + list: any[], + iterator: string, + context?: any): { [key: string]: any[]; }; + + /** + * Sorts a list into groups and returns a count for the number of objects in each group. Similar + * to groupBy, but instead of returning a list of values, returns a count for the number of values + * in that group. + * @param list Group elements in this list and then count the number of elements in each group. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the number of elements in that group. + **/ + countBy( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: number; }; + /** + * Sorts a list into groups and returns a count for the number of objects in each group. Similar + * to groupBy, but instead of returning a list of values, returns a count for the number of values + * in that group. + * @param list Group elements in this list and then count the number of elements in each group. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the number of elements in that group. + **/ + countBy( + list: any[], + iterator: string, + context?: any): { [key: string]: number; }; + + /** + * Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle. + * @param list List to shuffle. + * @return Shuffled copy of `list`. + **/ + shuffle(list: any[]): any[]; + + /** + * Converts the list (anything that can be iterated over), into a real Array. Useful for transmuting + * the arguments object. + * @param list object to transform into an array. + * @return `list` as an array. + **/ + toArray(list: any): any[]; + + /** + * Return the number of values in the list. + * @param list Count the number of values/elements in this list. + * @return Number of values in `list`. + **/ + size(list: any): number; + + /********* + * Arrays * + **********/ + + /** + * Returns the first element of an array. Passing n will return the first n elements of the array. + * @param array Retrieves the first element of this array. + * @return Returns the first element of `array`. + **/ + first(array: any[]): any; + /** + * Returns the first element of an array. Passing n will return the first n elements of the array. + * @param array Retreives the first `n` elements of this array. + * @param n Return more than one element from `array`. + * @return Returns the first `n` elements from `array. + **/ + first(array: any[], n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + head(array: any[]): any; + /** + * Alias for 'first'. + * @see first + **/ + head(array: any[], n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + take(array: any[]): any; + /** + * Alias for 'first'. + * @see first + **/ + take(array: any[], n: number): any[]; + + /** + * Returns everything but the last entry of the array. Especially useful on the arguments object. + * Pass n to exclude the last n elements from the result. + * @param array Retreive all elements except the last `n`. + * @param n Leaves this many elements behind, optional. + * @return Returns everything but the last `n` elements of `array`. + **/ + initial(array: any[], n?: number): any[]; + + /** + * Returns the last element of an array. Passing n will return the last n elements of the array. + * @param array Retrieves the last element of this array. + * @return Returns the last element of `array`. + **/ + last(array: any[]): any; + /** + * Returns the last element of an array. Passing n will return the last n elements of the array. + * @param array Retreives the last `n` elements of this array. + * @param n Return more than one element from `array`. + * @return Returns the last `n` elements from `array. + **/ + last(array: any[], n: number): any[]; + + /** + * Returns the rest of the elements in an array. Pass an index to return the values of the array + * from that index onward. + * @param array The array to retrieve all but the first `index` elements. + * @param index The index to start retrieving elements forward from, optional, default = 1. + * @return Returns the elements of `array` from `index` to the end of `array`. + **/ + rest(array: any[], index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + tail(array: any[], index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + drop(array: any[], index?: number): any[]; + + /** + * Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", + * undefined and NaN are all falsy. + * @param array Array to compact. + * @return Copy of `array` without false values. + **/ + compact(array: any[]): any[]; + + /** + * Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will + * only be flattened a single level. + * @param array The array to flatten. + * @param shallow If true then only flatten one level, optional, default = false. + * @return `array` flattened. + **/ + flatten(array: any, shallow?: bool): any; + + /** + * Returns a copy of the array with all instances of the values removed. + * @param array The array to remove `values` from. + * @param values The values to remove from `array`. + * @return Copy of `array` without `values`. + **/ + without(array: any[], ...values: any[]): any[]; + + /** + * Computes the union of the passed-in arrays: the list of unique items, in order, that are + * present in one or more of the arrays. + * @param arrays Array of arrays to compute the union of. + * @return The union of elements within `arrays`. + **/ + union(...arrays: any[][]): any[]; + + /** + * 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. + * @param arrays Array of arrays to compute the intersection of. + * @return The intersection of elements within `arrays`. + **/ + intersection(...arrays: any[][]): any[]; + + /** + * Similar to without, but returns the values from array that are not present in the other arrays. + * @param array Keeps values that are within `others`. + * @param others The values to keep within `array`. + * @return Copy of `array` with only `others` values. + **/ + difference(array: any[], ...others: any[]): any[]; + + /** + * 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. If + * you want to compute unique items based on a transformation, pass an iterator function. + * @param array Array to remove duplicates from. + * @param isSorted True if `array` is already sorted, optiona, default = false. + * @param iterator Transform the elements of `array` before comparisons for uniqueness. + * @param context 'this' object in `iterator`, optional. + * @return Copy of `array` where all elements are unique. + **/ + uniq( + array: any[], + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * 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. If + * you want to compute unique items based on a transformation, pass an iterator function. + * @param array Array to remove duplicates from. + * @param iterator Transform the elements of `array` before comparisons for uniqueness. + * @param context 'this' object in `iterator`, optional. + * @return Copy of `array` where all elements are unique. + **/ + uniq( + array: any[], + iterator?: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + + /** + * Alias for 'uniq'. + * @see uniq + **/ + unique(array: any[], + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any): any[]; + + /** + * 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. + * If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion. + * @param arrays The arrays to merge/zip. + * @return Zipped version of `arrays`. + **/ + zip(...arrays: any[][]): any[][]; + + /** + * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a + * list of keys, and a list of values. + * @param keys Key array. + * @param values Value array. + * @return An object containing the `keys` as properties and `values` as the property values. + **/ + object(keys: string[], values: any[]): any; + /** + * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a + * list of keys, and a list of values. + * @param keyValuePairs Array of [key, value] pairs. + * @return An object containing the `keys` as properties and `values` as the property values. + **/ + object(...keyValuePairs: any[][]): any; + + /** + * 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 ... or, pass a number + * as the third argument in order to look for the first matching value in the array after the given index. + * @param array The array to search for the index of `value`. + * @param value The value to search for within `array`. + * @param isSorted True if the array is already sorted, optional, default = false. + * @return The index of `value` within `array`. + **/ + indexOf(array: any[], value: any, isSorted?: bool): number; + + /** + * 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. Pass fromIndex to start your search at a given index. + * @param array The array to search for the last index of `value`. + * @param value The value to search for within `array`. + * @param from The starting index for the search, optional. + * @return The index of the last occurance of `value` within `array`. + **/ + lastIndexOf(array: any[], value: any, from?: number): number; + + /** + * 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, including the value you pass. + * @param list The sorted list. + * @param value The value to determine its index within `list`. + * @param iterator Iterator to compute the sort ranking of each value, optional. + * @return The index where `value` should be inserted into `list`. + **/ + sortedIndex(list: any[], value: any, iterator?: (element: any) => number): number; + + /** + * 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. + * @param start Start here. + * @param stop Stop here. + * @param step The number to count up by each iteration, optional, default = 1. + * @return Array of numbers from `start` to `stop` with increments of `step`. + **/ + range(start: number, stop: number, step?: number): number[]; + /** + * 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. + * @param stop Stop here. + * @return Array of numbers from 0 to `stop` with increments of 1. + * @note If start is not specified the implementation will never pull the step (step = arguments[2] || 0) + **/ + range(stop: number): number[]; + + /************ + * Functions * + *************/ + + /** + * 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 partial application. + * @param fn The function to bind `this` to `object`. + * @param object The `this` pointer whenever `fn` is called. + * @param arguments Additional arguments to pass to `fn` when called. + * @return `fn` with `this` bound to `object`. + **/ + bind(fn: Function, object: any, ...arguments: any[]): Function; + + + /** + * 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. + * @param object The object to bind the methods `methodName` to. + * @param methodNames The methods to bind to `object`, optional and if not provided all of `object`'s + * methods are bound. + **/ + bindAll(object: any, ...methodNames: string[]): void; + + /** + * 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. The default hashFunction just uses the first argument to the + * memoized function as the key. + * @param fn Computationally expensive function that will now memoized results. + * @param hashFn Hash function for storing the result of `fn`. + * @return Memoized version of `fn`. + **/ + memoize(fn: Function, hashFn?: (n: any) => string): Function; + + /** + * 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. + * @param fn Function to delay `waitMS` amount of ms. + * @param waitMS The amount of milliseconds to delay `fn`. + * @arguments Additional arguments to pass to `fn`. + **/ + delay(fn: Function, waitMS: number, ...arguments: any[]): void; + + /** + * 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. If you pass the optional arguments, they will be forwarded on + * to the function when it is invoked. + * @param fn The function to defer. + * @param arguments Additional arguments to pass to `fn`. + **/ + defer(fn: Function, ...arguments: any[]): void; + + /** + * Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, + * will only actually call the original function at most once per every wait milliseconds. Useful for + * rate-limiting events that occur faster than you can keep up with. + * @param fn Function to throttle `waitMS` ms. + * @param waitMS The number of milliseconds to wait before `fn` can be invoked again. + * @return `fn` with a throttle of `waitMS`. + **/ + throttle(fn: Function, waitMS: number): Function; + + /** + * Creates and returns a new debounced version of the passed function that will postpone its execution + * until after wait milliseconds have elapsed since the last time it was invoked. 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, and so on. + * + * Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead + * of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double + *-clicks on a "submit" button from firing a second time. + * @param fn Function to debounce `waitMS` ms. + * @param waitMS The number of milliseconds to wait before `fn` can be invoked again. + * @param immediate True if `fn` should be invoked on the leading edge of `waitMS` instead of the trailing edge. + * @return Debounced version of `fn` that waits `waitMS` ms when invoked. + **/ + debounce(fn: Function, waitMS: number, immediate?: bool): Function; + + /** + * Creates a version of the function that can only be called one time. Repeated calls to the modified + * function will have no effect, returning the value from the original call. Useful for initialization + * functions, instead of having to set a boolean flag and then check it later. + * @param fn Function to only execute once. + * @return Copy of `fn` that can only be invoked once. + **/ + once(fn: Function): Function; + + /** + * Creates a version of the function that will only be run after first being called count times. Useful + * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, + * before proceeding. + * @param count Number of times to be called before actually executing. + * @fn The function to defer execution `count` times. + * @return Copy of `fn` that will not execute until it is invoked `count` times. + **/ + after(count: number, fn: Function): Function; + + /** + * 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. + * @param fn Function to wrap. + * @param wrapper The function that will wrap `fn`. + * @return Wrapped version of `fn. + **/ + wrap(fn: Function, wrapper: (fn: Function, ...args: any[]) => any): Function; + + /** + * 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())). + * @param functions List of functions to compose. + * @return Composition of `functions`. + **/ + compose(...functions: Function[]): Function; + + /********** + * Objects * + ***********/ + + /** + * Retrieve all the names of the object's properties. + * @param object Retreive the key or property names from this object. + * @return List of all the property names on `object`. + **/ + keys(object: any): string[]; + + /** + * Return all of the values of the object's properties. + * @param object Retreive the values of all the properties on this object. + * @return List of all the values on `object`. + **/ + values(object: any): any[]; + + /** + * Convert an object into a list of [key, value] pairs. + * @param object Convert this object to a list of [key, value] pairs. + * @return List of [key, value] pairs on `object`. + **/ + pairs(object: any): any[][]; + + /** + * Returns a copy of the object where the keys have become the values and the values the keys. + * For this to work, all of your object's values should be unique and string serializable. + * @param object Object to invert key/value pairs. + * @return An inverted key/value paired version of `object`. + **/ + invert(object: any): any; + + /** + * 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. + * @param object Object to pluck all function property names from. + * @return List of all the function names on `object`. + **/ + functions(object: any): string[]; + + /** + * Copy all of the properties in the source objects over to the destination object, and return + * the destination object. It's in-order, so the last source will override properties of the + * same name in previous arguments. + * @param destination Object to extend all the properties from `sources`. + * @param sources Extends `destination` with all properties from these source objects. + * @return `destination` extended with all the properties from the `sources` objects. + **/ + extend(destination: any, ...sources: any[]): any; + + /** + * Return a copy of the object, filtered to only have values for the whitelisted keys + * (or array of valid keys). + * @param object Object to strip unwanted key/value pairs. + * @keys The key/value pairs to keep on `object`. + * @return Copy of `object` with only the `keys` properties. + **/ + pick(object: any, ...keys: string[]): any; + + /** + * Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). + * @param object Object to strip unwanted key/value pairs. + * @param keys The key/value pairs to remove on `object`. + * @return Copy of `object` without the `keys` properties. + **/ + omit(object: any, ...keys: string[]): any; + + /** + * Fill in null and undefined properties in object with values from the defaults objects, + * and return the object. As soon as the property is filled, further defaults will have no effect. + * @param object Fill this object with default values. + * @param defaults The default values to add to `object`. + * @return `object` with added `defaults` values. + **/ + defaults(object: any, ...defaults: any[]): any; + + /** + * Create a shallow-copied clone of the object. + * Any nested objects or arrays will be copied by reference, not duplicated. + * @param object Object to clone. + * @return Copy of `object`. + **/ + clone(object: any): any; + /** + * Create a shallow-copied clone of the object. + * Any nested objects or arrays will be copied by reference, not duplicated. + * @param list List to clone. + * @return Copy of `list`. + **/ + clone(list: any[]): any[]; + + /** + * 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. + * @param object Argument to `interceptor`. + * @param intercepter The function to modify `object` before continuing the method chain. + * @return Modified `object`. + **/ + tap(object: any, intercepter: Function): any; + + /** + * Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe + * reference to the hasOwnProperty function, in case it's been overridden accidentally. + * @param object Object to check for `key`. + * @param key The key to check for on `object`. + * @return True if `key` is a property on `object`, otherwise false. + **/ + has(object: any, key: string): bool; + + /** + * Performs an optimized deep comparison between the two objects, + * to determine if they should be considered equal. + * @param object Compare to `other`. + * @param other Compare to `object`. + * @return True if `object` is equal to `other`. + **/ + isEqual(object: any, other: any): bool; + + /** + * Returns true if object contains no values. + * @param object Check if this object has no properties or values. + * @return True if `object` is empty. + **/ + isEmpty(object: any): bool; + /** + * Returns true if the list contains no values. + * @param object Check if this list has no elements. + * @return True if `list` is empty. + **/ + isEmpty(list: any[]): bool; + + /** + * Returns true if object is a DOM element. + * @param object Check if this object is a DOM element. + * @return True if `object` is a DOM element, otherwise false. + **/ + isElement(object: any): bool; + + /** + * Returns true if object is an Array. + * @param object Check if this object is an Array. + * @return True if `object` is an Array, otherwise false. + **/ + isArray(object: any): bool; + + /** + * Returns true if value is an Object. Note that JavaScript arrays and functions are objects, + * while (normal) strings and numbers are not. + * @param object Check if this object is an Object. + * @return True of `object` is an Object, otherwise false. + **/ + isObject(object: any): bool; + + /** + * Returns true if object is an Arguments object. + * @param object Check if this object is an Arguments object. + * @return True if `object` is an Arguments object, otherwise false. + **/ + isArguments(object: any): bool; + + /** + * Returns true if object is a Function. + * @param object Check if this object is a Function. + * @return True if `object` is a Function, otherwise false. + **/ + isFunction(object: any): bool; + + /** + * Returns true if object is a String. + * @param object Check if this object is a String. + * @return True if `object` is a String, otherwise false. + **/ + isString(object: any): bool; + + /** + * Returns true if object is a Number (including NaN). + * @param object Check if this object is a Number. + * @return True if `object` is a Number, otherwise false. + **/ + isNumber(object: any): bool; + + /** + * Returns true if object is a finite Number. + * @param object Check if this object is a finite Number. + * @return True if `object` is a finite Number. + **/ + isFinite(object: any): bool; + + /** + * Returns true if object is either true or false. + * @param object Check if this object is a bool. + * @return True if `object` is a bool, otherwise false. + **/ + isBoolean(object: any): bool; + + /** + * Returns true if object is a Date. + * @param object Check if this object is a Date. + * @return True if `object` is a Date, otherwise false. + **/ + isDate(object: any): bool; + + /** + * Returns true if object is a RegExp. + * @param object Check if this object is a RegExp. + * @return True if `object` is a RegExp, otherwise false. + **/ + isRegExp(object: any): bool; + + /** + * 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. + * @param object Check if this object is NaN. + * @return True if `object` is NaN, otherwise false. + **/ + isNaN(object: any): bool; + + /** + * Returns true if the value of object is null. + * @param object Check if this object is null. + * @return True if `object` is null, otherwise false. + **/ + isNull(object: any): bool; + + /** + * Returns true if value is undefined. + * @param object Check if this object is undefined. + * @return True if `object` is undefined, otherwise false. + **/ + isUndefined(object: any): bool; + + /********** + * Utility * + ***********/ + + /** + * Give control of the "_" variable back to its previous owner. + * Returns a reference to the Underscore object. + * @return Underscore object reference. + **/ + noConflict(): Underscore; + + /** + * 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. + * @param value Identity of this object. + * @return `value`. + **/ + identity(value: any): any; + + /** + * Invokes the given iterator function n times. + * Each invocation of iterator is called with an index argument + * @param n Number of times to invoke `iterator`. + * @param iterator Function iterator to invoke `n` times. + * @param context `this` object in `iterator`, optional. + **/ + times(n: number, iterator: (n: number) => any , context?: any): any[]; + + /** + * Returns a random integer between min and max, inclusive. If you only pass one argument, + * it will return a number between 0 and that number. + * @param max The maximum random number. + * @return A random number between 0 and `max`. + **/ + random(max: number): number; + /** + * Returns a random integer between min and max, inclusive. If you only pass one argument, + * it will return a number between 0 and that number. + * @param min The minimum random number. + * @param max The maximum random number. + * @return A random number between `min` and `max`. + **/ + random(min: number, max: number): number; + + /** + * 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. + * @param object Mixin object containing key/function pairs to add to the Underscore object. + **/ + mixin(object: any): void; + + /** + * 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. Without prefix, returns an integer. + * @return Unique number ID. + **/ + uniqueId(): number; + /** + * 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. Without prefix, returns an integer. + * @param prefix A prefix string to start the unique ID with. + * @return Unique string ID beginning with `prefix`. + **/ + uniqueId(prefix: string): string; + + /** + * Escapes a string for insertion into HTML, replacing &, <, >, ", ', and / characters. + * @param str Raw string to escape. + * @return `str` HTML escaped. + **/ + escape(str: string): string; + + /** + * If the value of the named property is a function then invoke it; otherwise, return it. + * @param object Object to maybe invoke function `property` on. + * @param property The function by name to invoke on `object`. + * @return The result of invoking the function `property` on `object. + **/ + result(object: any, property: string): any; + + /** + * 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 + * <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %> When + * you evaluate a template function, pass in a data object that has properties corresponding to + * the template's free variables. If you're writing a one-off, you can pass the data object as + * the second parameter to template in order to render immediately instead of returning a template + * function. The settings argument should be a hash containing any _.templateSettings that should + * be overridden. + * @param templateString Underscore HTML template. + * @param data Data to use when compiling `templateString`. + * @param settings Settings to use while compiling. + * @return Returns the compiled Underscore HTML template. + **/ + template(templateString: string, data?: any, settings?: UnderscoreTemplateSettings): any; + + /** + * By default, Underscore uses ERB-style template delimiters, change the + * following template settings to use alternative delimiters. + **/ + templateSettings: UnderscoreTemplateSettings; + + /*********** + * Chaining * + ************/ + + /** + * Returns a wrapped object. Calling methods on this object will continue to return wrapped objects + * until value() is used. + * @param obj Object to chain. + * @return Wrapped `obj`. + **/ + chain(obj: any): UnderscoreOOPWrapper; + + /** + * Extracts the value of a wrapped object. + * @param obj Wrapped object to extract the value from. + * @return Value of `obj`. + **/ + value(obj: any): any; + + /************** + * OOP Wrapper * + **************/ + + /** + * Underscore OOP Wrapper, all Underscore functions that take an object + * as the first parameter can be invoked through this function. + * @param key First argument to Underscore object functions. + **/ + (obj: any): UnderscoreOOPWrapper; +} + +/** +* underscore.js template settings, set templateSettings or pass as an argument +* to 'template()' to overide defaults. +**/ +interface UnderscoreTemplateSettings { + /** + * Default value is '/<%([\s\S]+?)%>/g'. + **/ + evaluate?: RegExp; + + /** + * Default value is '/<%=([\s\S]+?)%>/g'. + **/ + interpolate?: RegExp; + + /** + * Default value is '/<%-([\s\S]+?)%>/g'. + **/ + escape?: RegExp; +} + +interface UnderscoreOOPWrapper { + + /************** + * Collections * + **************/ + + /** + * Wrapped type `any[]`. + * @see _.each + **/ + each( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * Wrapped type `object`. + * @see _.each + **/ + each( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * Alias for 'each'. + * @see each + **/ + forEach( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * Alias for 'each'. + * @see each + **/ + forEach( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Wrapped type `object`. + * @see _.map + **/ + map( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * Alias for 'map'. + * @see map + **/ + collect( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Alias for 'map'. + * @see map + **/ + collect( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.reduce + **/ + reduce( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + inject( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + foldl( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Wrapped type `any[]`. + * @see _.reduceRight + **/ + reduceRight( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduceRight'. + * @see reduceRight + **/ + foldr( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Wrapped type `any[]`. + * @see _.find + **/ + find( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + /** + * Alias for 'find'. + * @see find + **/ + detect( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + + /** + * Wrapped type `any[]`. + * @see _.filter + **/ + filter( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Alias for 'filter'. + * @see filter + **/ + select( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.where + **/ + where(list: any[], properties: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.reject + **/ + reject( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.all + **/ + all( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'all'. + * @see all + **/ + every( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Wrapped type `any[]`. + * @see _.any + **/ + any( + list: any[], + iterator?: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'any'. + * @see any + **/ + some( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Wrapped type `any[]`. + * @see _.contains + **/ + contains(value: any): bool; + + /** + * Alias for 'contains'. + * @see contains + **/ + include(value: any): bool; + + /** + * Wrapped type `any[]`. + * @see _.invoke + **/ + invoke(methodName: string, ...arguments: any[]): void; + + /** + * Wrapped type `any[]`. + * @see _.pluck + **/ + pluck(propertyName: string): any[]; + + /** + * Wrapped type `number[]`. + * @see _.max + **/ + max(): number; + /** + * Wrapped type `any[]`. + * @see _.max + **/ + max( + iterator: (element: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Wrapped type `number[]`. + * @see _.min + **/ + min(): number; + /** + * Wrapped type `any[]`. + * @see _.min + **/ + min( + iterator: (obj: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Wrapped type `any[]`. + * @see _.sortBy + **/ + sortBy( + iterator: (element: any, index?: number, list?: any[]) => number, + context?: any): any[]; + /** + * Wrapped type `any[]`. + * @see _.sortBy + **/ + sortBy( + iterator: string, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.groupBy + **/ + groupBy( + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: any[]; }; + /** + * Wrapped type `any[]`. + * @see _.groupBy + **/ + groupBy( + iterator: string, + context?: any): { [key: string]: any[]; }; + + /** + * Wrapped type `any[]`. + * @see _.countBy + **/ + countBy( + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: number; }; + /** + * Wrapped type `any[]`. + * @see _.countBy + **/ + countBy( + iterator: string, + context?: any): { [key: string]: number; }; + + /** + * Wrapped type `any[]`. + * @see _.shuffle + **/ + shuffle(): any[]; + + /** + * Wrapped type `any`. + * @see _.toArray + **/ + toArray(): any[]; + + /** + * Wrapped type `any`. + * @see _.size + **/ + size(): number; + + /********* + * Arrays * + **********/ + + /** + * Wrapped type `any[]`. + * @see _.first + **/ + first(): any; + /** + * Wrapped type `any[]`. + * @see _.first + **/ + first(n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + head(): any; + /** + * Alias for 'first'. + * @see first + **/ + head(n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + take(): any; + /** + * Alias for 'first'. + * @see first + **/ + take(n: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.initial + **/ + initial(n?: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.last + **/ + last(): any; + /** + * Wrapped type `any[]`. + * @see _.last + **/ + last(n: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.rest + **/ + rest(index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + tail(index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + drop(index?: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.compact + **/ + compact(): any[]; + + /** + * Wrapped type `any`. + * @see _.flatten + **/ + flatten(shallow?: bool): any; + + /** + * Wrapped type `any[]`. + * @see _.without + **/ + without(...values: any[]): any[]; + + /** + * Wrapped type `any[][]`. + * @see _.union + **/ + union(...arrays: any[][]): any[]; + + /** + * Wrapped type `any[][]`. + * @see _.intersection + **/ + intersection(...arrays: any[][]): any[]; + + /** + * Wrapped type `any[]`. + * @see _.difference + **/ + difference(...others: any[]): any[]; + + /** + * Wrapped type `any[]`. + * @see _.uniq + **/ + uniq( + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Wrapped type `any[]`. + * @see _.uniq + **/ + uniq( + iterator?: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + + /** + * Alias for 'uniq'. + * @see uniq + **/ + unique( + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any): any[]; + + /** + * Wrapped type `any[][]`. + * @see _.zip + **/ + zip(...arrays: any[][]): any[][]; + + /** + * Wrapped type `any[][]`. + * @see _.object + **/ + object(...keyValuePairs: any[][]): any; + + /** + * Wrapped type `any[]`. + * @see _.indexOf + **/ + indexOf(value: any, isSorted?: bool): number; + + /** + * Wrapped type `any[]`. + * @see _.lastIndexOf + **/ + lastIndexOf(value: any, from?: number): number; + + /** + * Wrapped type `any[]`. + * @see _.sortedIndex + **/ + sortedIndex(value: any, iterator?: (element: any) => number): number; + + /** + * Wrapped type `number`. + * @see _.range + **/ + range(stop: number, step?: number): number[]; + /** + * Wrapped type `number`. + * @see _.range + **/ + range(): number[]; + + /************ + * Functions * + *************/ + + /** + * Wrapped type `Function`. + * @see _.bind + **/ + bind(object: any, ...arguments: any[]): Function; + + + /** + * Wrapped type `object`. + * @see _.bindAll + **/ + bindAll(...methodNames: string[]): void; + + /** + * Wrapped type `Function`. + * @see _.memoize + **/ + memoize(hashFn?: (n: any) => string): Function; + + /** + * Wrapped type `Function`. + * @see _.delay + **/ + delay(waitMS: number, ...arguments: any[]): void; + + /** + * Wrapped type `Function`. + * @see _.defer + **/ + defer(...arguments: any[]): void; + + /** + * Wrapped type `Function`. + * @see _.throttle + **/ + throttle(waitMS: number): Function; + + /** + * Wrapped type `Function`. + * @see _.debounce + **/ + debounce(waitMS: number, immediate?: bool): Function; + + /** + * Wrapped type `Function`. + * @see _.once + **/ + once(): Function; + + /** + * Wrapped type `number`. + * @see _.after + **/ + after(fn: Function): Function; + + /** + * Wrapped type `Function`. + * @see _.wrap + **/ + wrap(wrapper: (fn: Function, ...args: any[]) => any): Function; + + /** + * Wrapped type `Function[]`. + * @see _.compose + **/ + compose(...functions: Function[]): Function; + + /********** + * Objects * + ***********/ + + /** + * Wrapped type `object`. + * @see _.keys + **/ + keys(): string[]; + + /** + * Wrapped type `object`. + * @see _.values + **/ + values(): any[]; + + /** + * Wrapped type `object`. + * @see _.pairs + **/ + pairs(): any[][]; + + /** + * Wrapped type `object`. + * @see _.invert + **/ + invert(): any; + + /** + * Wrapped type `object`. + * @see _.functions + **/ + functions(): string[]; + + /** + * Wrapped type `object`. + * @see _.extend + **/ + extend(...sources: any[]): any; + + /** + * Wrapped type `object`. + * @see _.pick + **/ + pick(...keys: string[]): any; + + /** + * Wrapped type `object`. + * @see _.omit + **/ + omit(...keys: string[]): any; + + /** + * Wrapped type `object`. + * @see _.defaults + **/ + defaults(...defaults: any[]): any; + + /** + * Wrapped type `object`. + * @see _.clone + **/ + clone(object: any): any; + /** + * Wrapped type `any[]`. + * @see _.clone + **/ + clone(list: any[]): any[]; + + /** + * Wrapped type `object`. + * @see _.tap + **/ + tap(intercepter: Function): any; + + /** + * Wrapped type `object`. + * @see _.has + **/ + has(key: string): bool; + + /** + * Wrapped type `object`. + * @see _.isEqual + **/ + isEqual(other: any): bool; + + /** + * Wrapped type `object`. + * @see _.isEmpty + **/ + isEmpty(object: any): bool; + /** + * Wrapped type `any[]`. + * @see _.isEmpty + **/ + isEmpty(list: any[]): bool; + + /** + * Wrapped type `object`. + * @see _.isElement + **/ + isElement(): bool; + + /** + * Wrapped type `object`. + * @see _.isArray + **/ + isArray(): bool; + + /** + * Wrapped type `object`. + * @see _.isObject + **/ + isObject(): bool; + + /** + * Wrapped type `object`. + * @see _.isArguments + **/ + isArguments(): bool; + + /** + * Wrapped type `object`. + * @see _.isFunction + **/ + isFunction(): bool; + + /** + * Wrapped type `object`. + * @see _.isString + **/ + isString(): bool; + + /** + * Wrapped type `object`. + * @see _.isNumber + **/ + isNumber(): bool; + + /** + * Wrapped type `object`. + * @see _.isFinite + **/ + isFinite(): bool; + + /** + * Wrapped type `object`. + * @see _.isBoolean + **/ + isBoolean(): bool; + + /** + * Wrapped type `object`. + * @see _.isDate + **/ + isDate(): bool; + + /** + * Wrapped type `object`. + * @see _.isRegExp + **/ + isRegExp(): bool; + + /** + * Wrapped type `object`. + * @see _.isNaN + **/ + isNaN(): bool; + + /** + * Wrapped type `object`. + * @see _.isNull + **/ + isNull(): bool; + + /** + * Wrapped type `object`. + * @see _.isUndefined + **/ + isUndefined(): bool; + + /********** + * Utility * + ***********/ + + /** + * Wrapped type `any`. + * @see _.identity + **/ + identity(): any; + + /** + * Wrapped type `number`. + * @see _.times + **/ + times(iterator: (n: number) => any, context?: any): any[]; + + /** + * Wrapped type `number`. + * @see _.random + **/ + random(): number; + /** + * Wrapped type `number`. + * @see _.random + **/ + random(max: number): number; + + /** + * Wrapped type `object`. + * @see _.mixin + **/ + mixin(): void; + + /** + * Wrapped type `string`. + * @see _.uniqueId + **/ + uniqueId(): string; + + /** + * Wrapped type `string`. + * @see _.escape + **/ + escape(): string; + + /** + * Wrapped type `object`. + * @see _.result + **/ + result(property: string): any; + + /** + * Wrapped type `string`. + * @see _.template + **/ + template(data?: any, settings?: UnderscoreTemplateSettings): any; + + /*********** + * Chaining * + ************/ + + /** + * Wrapped type `any`. + * @see _.chain + **/ + chain(): any; + + /** + * Wrapped type `any`. + * @see _.value + **/ + value(): any; +} + +declare var _: Underscore; diff --git a/underscore/underscore-typed.d.ts b/underscore/underscore-typed.d.ts index d3fadb0d38..86077aa184 100644 --- a/underscore/underscore-typed.d.ts +++ b/underscore/underscore-typed.d.ts @@ -1,3097 +1,2060 @@ -// underscore-1.4.2.d.ts -// (c) 2012 Josh Baldwin -// underscore.d.ts may be freely distributed under the MIT license. -// For all details and documentation: -// https://github.com/jbaldwin/underscore.d.ts - -interface Underscore { - - /************** - * Collections * - ***************/ - - /** - * 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. - **/ - each( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => any, - context?: any): void; - each( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => any, - context?: any): void; - each( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => any, - context?: any): void; - each( - obj: Object, - iterator: (value: any, key?: string, object?: Object) => any, - context?: any): void; - - /** - * Alias for 'each'. - **/ - forEach( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => any, - context?: any): void; - forEach( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => any, - context?: any): void; - forEach( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => any, - context?: any): void; - forEach( - obj: Object, - iterator: (value: any, key?: string, object?: Object) => any, - context?: any): void; - - /** - * 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). - **/ - map( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => string, - context?: any): string[]; - map( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => number, - context?: any): number[]; - map( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => any, - context?: any): any[]; - map( - obj: Object, - iterator: (value: any, key?: string, object?: Object) => any, - context?: any): any[]; - - /** - * Alias for 'map'. - **/ - collect( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => string, - context?: any): string[]; - collect( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => number, - context?: any): number[]; - collect( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => any, - context?: any): any[]; - collect( - obj: Object, - iterator: (value: any, key?: string, object?: Object) => any, - context?: any): any[]; - - /** - * 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. The iterator is passed four arguments: the memo, then the value - * and index (or key) of the iteration, and finally a reference to the entire list. - **/ - reduce( - list: string[], - iterator: (memo: string, element: string, index?: number, list?: string[]) => string, - memo: string, - context?: any): string; - reduce( - list: number[], - iterator: (memo: number, element: number, index?: number, list?: number[]) => number, - memo: number, - context?: any): number; - reduce( - list: any[], - iterator: (memo: any, element: any, index?: number, list?: any[]) => any, - memo: any, - context?: any): any; - - /** - * Alias for 'reduce'. - **/ - inject( - list: string[], - iterator: (memo: string, element: string, index?: number, list?: string[]) => string, - memo: string, - context?: any): string; - inject( - list: number[], - iterator: (memo: number, element: number, index?: number, list?: number[]) => number, - memo: number, - context?: any): number; - inject( - list: any[], - iterator: (memo: any, element: any, index?: number, list?: any[]) => any, - memo: any, - context?: any): any; - - /** - * Alias for 'reduce'. - **/ - foldl( - list: string[], - iterator: (memo: string, element: string, index?: number, list?: string[]) => string, - memo: string, - context?: any): string; - foldl( - list: number[], - iterator: (memo: number, element: number, index?: number, list?: number[]) => number, - memo: number, - context?: any): number; - foldl( - list: any[], - iterator: (memo: any, element: any, index?: number, list?: any[]) => any, - memo: any, - context?: any): any; - - /** - * 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. - **/ - reduceRight( - list: string[], - iterator: (memo: string, element: string, index?: number, list?: string[]) => string, - memo: string, - context?: any): string; - reduceRight( - list: number[], - iterator: (memo: number, element: number, index?: number, list?: number[]) => number, - memo: number, - context?: any): number; - reduceRight( - list: any[], - iterator: (memo: any, element: any, index?: number, list?: any[]) => any, - memo: any, - context?: any): any; - - /** - * Alias for 'reduceRight'. - **/ - foldr( - list: string[], - iterator: (memo: string, element: string, index?: number, list?: string[]) => string, - memo: string, - context?: any): string; - foldr( - list: number[], - iterator: (memo: number, element: number, index?: number, list?: number[]) => number, - memo: number, - context?: any): number; - foldr( - list: any[], - iterator: (memo: any, element: any, index?: number, list?: any[]) => any, - memo: any, - context?: any): any; - - /** - * 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. - **/ - find( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): string; - find( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => bool, - context?: any): number; - find( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): any; - - /** - * Alias for 'find'. - **/ - detect( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): string; - detect( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => bool, - context?: any): number; - detect( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): any; - - - /** - * 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( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): string[]; - filter( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => bool, - context?: any): number[]; - filter( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): any[]; - - /** - * Alias for 'filter'. - **/ - select( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): string[]; - select( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => bool, - context?: any): number[]; - select( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): any[]; - - /** - * Looks through each value in the list, returning an array of all the values that contain all - * of the key-value pairs listed in properties. - **/ - where(list: any[], properties: any): any[]; - - /** - * Returns the values in list without the elements that the truth test (iterator) passes. - * The opposite of filter. - **/ - reject( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): string[]; - reject( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => bool, - context?: any): number[]; - reject( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): any[]; - - /** - * Returns true if all of the values in the list pass the iterator truth test. Delegates to the - * native method every, if present. - **/ - all( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): bool; - all( - list: number[], - iterator: (element: number, index?: number, list?: string[]) => bool, - context?: any): bool; - all( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): bool; - - /** - * Alias for 'all'. - **/ - every( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): bool; - every( - list: number[], - iterator: (element: number, index?: number, list?: string[]) => bool, - context?: any): bool; - every( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): bool; - - /** - * 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. - **/ - any( - list: string[], - iterator?: (element: string, index?: number, list?: string[]) => bool, - context?: any): bool; - any( - list: number[], - iterator?: (element: number, index?: number, list?: string[]) => bool, - context?: any): bool; - any( - list: any[], - iterator?: (element: any, index?: number, list?: any[]) => bool, - context?: any): bool; - - /** - * Alias for 'any'. - **/ - some( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): bool; - some( - list: number[], - iterator: (element: number, index?: number, list?: string[]) => bool, - context?: any): bool; - some( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): bool; - - /** - * Returns true if the value is present in the list. Uses indexOf internally, - * if list is an Array. - **/ - contains(list: string[], value: string): bool; - contains(list: number[], value: number): bool; - contains(list: any[], value: any): bool; - - /** - * Alias for 'contains'. - **/ - include(list: string[], value: string): bool; - include(list: number[], value: number): bool; - include(list: any[], value: any): bool; - - /** - * 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. - **/ - invoke(list: string[], methodName: string, ...arguments: any[]): void; - invoke(list: number[], methodName: string, ...arguments: any[]): void; - invoke(list: any[], methodName: string, ...arguments: any[]): void; - - /** - * A convenient version of what is perhaps the most common use-case for map: extracting a list of - * property values. - **/ - pluck(list: any[], propertyName: string): any[]; - - /** - * 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. - **/ - max(list: number[]): number; - max( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => number, - context?: any): any; - - /** - * 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. - **/ - min(list: number[]): number; - min( - list: any[], - iterator: (obj: any, index?: number, list?: any[]) => number, - context?: any): any; - - /** - * Returns a sorted copy of list, ranked in ascending order by the results of running each value - * through iterator. Iterator may also be the string name of the property to sort by (eg. length). - **/ - sortBy( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => number, - context?: any): string[]; - sortBy( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => number, - context?: any): number[]; - sortBy( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => number, - context?: any): any[]; - sortBy( - list: string[], - iterator: string, - context?: any): string[]; - sortBy( - list: number[], - iterator: string, - context?: any): number[]; - sortBy( - list: any[], - iterator: string, - context?: any): any[]; - - /** - * Splits a collection into sets, grouped by the result of running each value through iterator. - * If iterator is a string instead of a function, groups by the property named by iterator on - * each of the values. - **/ - groupBy( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => string, - context?: any): { [key: string]: string[]; }; - groupBy( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => string, - context?: any): { [key: string]: number[]; }; - groupBy( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => string, - context?: any): { [key: string]: any[]; }; - groupBy( - list: string[], - iterator: string, - context?: any): { [key: string]: string[]; }; - groupBy( - list: number[], - iterator: string, - context?: any): { [key: string]: number[]; }; - groupBy( - list: any[], - iterator: string, - context?: any): { [key: string]: any[]; }; - - /** - * Sorts a list into groups and returns a count for the number of objects in each group. Similar - * to groupBy, but instead of returning a list of values, returns a count for the number of values - * in that group. - **/ - countBy( - list: string[], - iterator: (element: string, index?: number, list?: string[]) => string, - context?: any): { [key: string]: number; }; - countBy( - list: number[], - iterator: (element: number, index?: number, list?: number[]) => string, - context?: any): { [key: string]: number; }; - countBy( - list: any[], - iterator: (element: any, index?: number, list?: any[]) => string, - context?: any): { [key: string]: number; }; - countBy( - list: string[], - iterator: string, - context?: any): { [key: string]: number; }; - countBy( - list: number[], - iterator: string, - context?: any): { [key: string]: number; }; - countBy( - list: any[], - iterator: string, - context?: any): { [key: string]: number; }; - - /** - * Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle. - **/ - shuffle(list: string[]): string[]; - shuffle(list: number[]): number[]; - shuffle(list: any[]): any[]; - - /** - * Converts the list (anything that can be iterated over), into a real Array. Useful for transmuting - * the arguments object. - **/ - toArray(list: any): any[]; - - /** - * Return the number of values in the list. - **/ - size(list: any): number; - - /********* - * Arrays * - **********/ - - /** - * Returns the first element of an array. Passing n will return the first n elements of the array. - **/ - first(array: string[]): string; - first(array: string[], n: number): string[]; - first(array: number[]): number; - first(array: number[], n: number): number[]; - first(array: any[]): any; - first(array: any[], n: number): any[]; - - /** - * Alias for 'first'. - **/ - head(array: string[]): string; - head(array: string[], n: number): string[]; - head(array: number[]): number; - head(array: number[], n: number): number[]; - head(array: any[]): any; - head(array: any[], n: number): any[]; - - /** - * Alias for 'first'. - **/ - take(array: string[]): string; - take(array: string[], n: number): string[]; - take(array: number[]): number; - take(array: number[], n: number): number[]; - take(array: any[]): any; - take(array: any[], n: number): any[]; - - /** - * Returns everything but the last entry of the array. Especially useful on the arguments object. - * Pass n to exclude the last n elements from the result. - **/ - initial(array: string[], n?: number): string[]; - initial(array: number[], n?: number): number[]; - initial(array: any[], n?: number): any[]; - - /** - * Returns the last element of an array. Passing n will return the last n elements of the array. - **/ - last(array: string[]): string; - last(array: string[], n: number): string[]; - last(array: number[]): number; - last(array: number[], n: number): number[]; - last(array: any[]): any; - last(array: any[], n: number): any[]; - - /** - * Returns the rest of the elements in an array. Pass an index to return the values of the array - * from that index onward. - **/ - rest(array: string[], index?: number): string[]; - rest(array: number[], index?: number): number[]; - rest(array: any[], index?: number): any[]; - - /** - * Alias for 'rest'. - **/ - tail(array: string[], index?: number): string[]; - tail(array: number[], index?: number): number[]; - tail(array: any[], index?: number): any[]; - - /** - * Alias for 'rest'. - **/ - drop(array: string[], index?: number): string[]; - drop(array: number[], index?: number): number[]; - drop(array: any[], index?: number): any[]; - - /** - * Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", - * undefined and NaN are all falsy. - **/ - compact(array: string[]): string[]; - compact(array: number[]): number[]; - compact(array: bool[]): bool[]; - compact(array: any[]): any[]; - - /** - * Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will - * only be flattened a single level. - **/ - flatten(array: string[], shallow?: bool): string[]; - flatten(array: string[][], shallow?: bool): string[]; - flatten(array: number[], shallow?: bool): number[]; - flatten(array: number[][], shallow?: bool): number[]; - flatten(array: any[], shallow?: bool): any[]; - flatten(array: any[][], shallow?: bool): any[]; - - /** - * Returns a copy of the array with all instances of the values removed. - **/ - without(array: string[], ...values: string[]): string[]; - without(array: number[], ...values: number[]): number[]; - without(array: any[], ...values: any[]): any[]; - - /** - * Computes the union of the passed-in arrays: the list of unique items, in order, that are - * present in one or more of the arrays. - **/ - union(...arrays: string[][]): string[]; - union(...arrays: number[][]): number[]; - union(...arrays: any[][]): any[]; - - /** - * 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. - **/ - intersection(...arrays: string[][]): string[]; - intersection(...arrays: number[][]): number[]; - intersection(...arrays: any[][]): any[]; - - /** - * Similar to without, but returns the values from array that are not present in the other arrays. - **/ - difference(array: string[], ...others: string[]): string[]; - difference(array: number[], ...others: number[]): number[]; - difference(array: any[], ...others: any[]): any[]; - - /** - * 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. If - * you want to compute unique items based on a transformation, pass an iterator function. - **/ - uniq(array: string[], isSorted?: bool, iterator?: (element: string, index?: number, list?: string[]) => string): string[]; - uniq(array: number[], isSorted?: bool, iterator?: (element: number, index?: number, list?: number[]) => number): number[]; - uniq(array: any[], isSorted?: bool, iterator?: (element: any, index?: number, list?: any[]) => any): any[]; - - /** - * Alias for 'uniq'. - **/ - unique(array: string[], isSorted?: bool, iterator?: (element: string, index?: number, list?: string[]) => string): string[]; - unique(array: number[], isSorted?: bool, iterator?: (element: number, index?: number, list?: number[]) => number): number[]; - unique(array: any[], isSorted?: bool, iterator?: (element: any, index?: number, list?: any[]) => any): any[]; - - /** - * 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. - * If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion. - **/ - zip(...arrays: string[][]): string[][]; - zip(...arrays: number[][]): number[][]; - zip(...arrays: any[][]): any[][]; - - /** - * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a - * list of keys, and a list of values. - **/ - object(keys: string[], values: any[]): any; - object(...keyValuePairs: any[][]): any; - - /** - * 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 ... or, pass a number - * as the third argument in order to look for the first matching value in the array after the given index. - **/ - indexOf(array: string[], value: string, isSorted?: bool): number; - indexOf(array: number[], value: number, isSorted?: bool): number; - indexOf(array: any[], value: any, isSorted?: bool): number; - - /** - * 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. Pass fromIndex to start your search at a given index. - **/ - lastIndexOf(array: string[], value: string, from?: number): number; - lastIndexOf(array: number[], value: number, from?: number): number; - lastIndexOf(array: any[], value: any, from?: number): number; - - /** - * 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, including the value you pass. - **/ - sortedIndex(list: string[], value: string, iterator?: (element: string) => number): number; - sortedIndex(list: number[], value: number, iterator?: (element: number) => number): number; - sortedIndex(list: any[], value: any, iterator?: (element: any) => number): number; - - /** - * 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. - **/ - range(start: number, stop: number, step?: number): number[]; - // If start is not specified the implementation will never pull the step (step = arguments[2] || 0) - range(stop: number): number[]; - - /************ - * Functions * - *************/ - - /** - * 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 partial application. - **/ - bind(fn: Function, object: any, ...arguments: any[]): Function; - - - /** - * 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. - **/ - bindAll(object: any, ...methodNames: string[]): void; - - /** - * 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. The default hashFunction just uses the first argument to the - * memoized function as the key. - **/ - memoize(fn: Function, hashFn?: (n: any) => string): Function; - - /** - * 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. - **/ - delay(fn: Function, waitMS: number, ...arguments: any[]): void; - - /** - * 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. If you pass the optional arguments, they will be forwarded on - * to the function when it is invoked. - **/ - defer(fn: Function, ...arguments: any[]): void; - - /** - * Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, - * will only actually call the original function at most once per every wait milliseconds. Useful for - * rate-limiting events that occur faster than you can keep up with. - **/ - throttle(fn: Function, waitMS: number): Function; - - /** - * Creates and returns a new debounced version of the passed function that will postpone its execution - * until after wait milliseconds have elapsed since the last time it was invoked. 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, and so on. - * - * Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead - * of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double - *-clicks on a "submit" button from firing a second time. - **/ - debounce(fn: Function, waitMS: number, immediate?: bool): Function; - - /** - * Creates a version of the function that can only be called one time. Repeated calls to the modified - * function will have no effect, returning the value from the original call. Useful for initialization - * functions, instead of having to set a boolean flag and then check it later. - **/ - once(fn: Function): Function; - - /** - * Creates a version of the function that will only be run after first being called count times. Useful - * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, - * before proceeding. - **/ - after(count: number, fn: Function): Function; - - /** - * 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. - **/ - wrap(fn: Function, wrapper: (fn: Function, ...args: any[]) => any): Function; - - /** - * 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())). - **/ - compose(...functions: Function[]): Function; - - /********** - * Objects * - ***********/ - - /** - * Retrieve all the names of the object's properties. - **/ - keys(object: any): string[]; - - /** - * Return all of the values of the object's properties. - **/ - values(object: any): any[]; - - /** - * Convert an object into a list of [key, value] pairs. - **/ - pairs(object: any): any[][]; - - /** - * Returns a copy of the object where the keys have become the values and the values the keys. - * For this to work, all of your object's values should be unique and string serializable. - **/ - invert(object: any): any; - - /** - * 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. - **/ - functions(object: any): string[]; - - /** - * Copy all of the properties in the source objects over to the destination object, and return - * the destination object. It's in-order, so the last source will override properties of the - * same name in previous arguments. - **/ - extend(destination: any, ...sources: any[]): any; - - /** - * Return a copy of the object, filtered to only have values for the whitelisted keys - * (or array of valid keys). - **/ - pick(object: any, ...keys: string[]): any; - - /** - * Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). - **/ - omit(object: any, ...keys: string[]): any; - - /** - * Fill in null and undefined properties in object with values from the defaults objects, - * and return the object. As soon as the property is filled, further defaults will have no effect. - **/ - defaults(object: any, ...defaults: any[]): any; - - /** - * Create a shallow-copied clone of the object. - * Any nested objects or arrays will be copied by reference, not duplicated. - **/ - clone(object: any): any; - clone(list: string[]): string[]; - clone(list: number[]): number[]; - clone(list: any[]): any[]; - - /** - * 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. - **/ - tap(object: any, intercepter: Function): any; - - /** - * Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe - * reference to the hasOwnProperty function, in case it's been overridden accidentally. - **/ - has(object: any, key: string): bool; - - /** - * Performs an optimized deep comparison between the two objects, - * to determine if they should be considered equal. - **/ - isEqual(object: any, other: any): bool; - - /** - * Returns true if object contains no values. - **/ - isEmpty(object: any): bool; - isEmpty(list: any[]): bool; - - /** - * Returns true if object is a DOM element. - **/ - isElement(object: any): bool; - - /** - * Returns true if object is an Array. - **/ - isArray(object: any): bool; - - /** - * Returns true if value is an any. Note that JavaScript arrays and functions are objects, - * while (normal) strings and numbers are not. - **/ - isObject(object: any): bool; - - /** - * Returns true if object is an Arguments object. - **/ - isArguments(object: any): bool; - - /** - * Returns true if object is a Function. - **/ - isFunction(object: any): bool; - - /** - * Returns true if object is a String. - **/ - isString(object: any): bool; - - /** - * Returns true if object is a Number (including NaN). - **/ - isNumber(object: any): bool; - - /** - * Returns true if object is a finite Number. - **/ - isFinite(object: any): bool; - - /** - * Returns true if object is either true or false. - **/ - isBoolean(object: any): bool; - - /** - * Returns true if object is a Date. - **/ - isDate(object: any): bool; - - /** - * Returns true if object is a RegExp. - **/ - isRegExp(object: any): bool; - - /** - * 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. - **/ - isNaN(object: any): bool; - - /** - * Returns true if the value of object is null. - **/ - isNull(object: any): bool; - - /** - * Returns true if value is undefined. - **/ - isUndefined(object: any): bool; - - /********** - * Utility * - ***********/ - - /** - * Give control of the "_" variable back to its previous owner. - * Returns a reference to the Underscore object. - **/ - noConflict(): Underscore; - - /** - * 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. - **/ - identity(value: string): string; - identity(value: string[]): string[]; - identity(value: number): number; - identity(value: number[]): number[]; - identity(value: bool): bool; - identity(value: any): any; - - /** - * Invokes the given iterator function n times. - * Each invocation of iterator is called with an index argument. - * @example - * - * _(3).times(function(n){ genie.grantWishNumber(n); }); - * - **/ - times(n: number, iterator: (n: number) => void , context?: any): void; - - /** - * Returns a random integer between min and max, inclusive. If you only pass one argument, - * it will return a number between 0 and that number. - **/ - random(max: number): number; - random(min: number, max: number): number; - - /** - * 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. - * @example - * - * _.mixin({ - * capitalize : function(string) { - * return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase(); - * } - * }); - * _("fabio").capitalize(); - * => "Fabio" - * - **/ - mixin(object: any): void; - - /** - * 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. Without prefix, returns an integer. - **/ - uniqueId(): number; - uniqueId(prefix: string): string; - - /** - * Escapes a string for insertion into HTML, replacing &, <, >, ", ', and / characters. - **/ - escape(str: string): string; - - /** - * If the value of the named property is a function then invoke it; otherwise, return it. - **/ - result(object: any, property: string): any; - - /** - * 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 - * <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %> When - * you evaluate a template function, pass in a data object that has properties corresponding to - * the template's free variables. If you're writing a one-off, you can pass the data object as - * the second parameter to template in order to render immediately instead of returning a template - * function. The settings argument should be a hash containing any _.templateSettings that should - * be overridden. - **/ - template(templateString: string, data?: any, settings?: UnderscoreTemplateSettings): any; - - // By default, Underscore uses ERB-style template delimiters, change the - // following template settings to use alternative delimiters. - templateSettings: UnderscoreTemplateSettings; - - /*********** - * Chaining * - ************/ - - /** - * Returns a wrapped object. Calling methods on this object will continue to return wrapped objects - * until value is used. - **/ - chain(obj: any): any; - - /** - * Extracts the value of a wrapped object. - **/ - value(s: string): string; - value(n: number): number; - value(s: string[]): string[]; - value(n: number[]): number[]; - value(obj: any): any; - value(obj: any[]): any[]; - - /************** - * OOP Wrapper * - **************/ - (key: string): UnderscoreStringOOPWrapper; - (list: string[]): UnderscoreStringArrayOOPWrapper; - (n: number): UnderscoreNumberOOPWrapper; - (list: number[]): UnderscoreNumberArrayOOPWrapper; - (obj: any): UnderscoreObjectOOPWrapper; - (list: any[]): UnderscoreObjectArrayOOPWrapper; -} - -/** -* underscore.js template settings, set templateSettings or pass as an argument -* to 'template()' to overide defaults. -**/ -interface UnderscoreTemplateSettings { - evaluate?: RegExp; - interpolate?: RegExp; - escape?: RegExp; -} - -/** -* Returned interface when calling the Underscore String OOP Wrapper. All "string" functions are -* available except the first argument is missing since that is the object being wrapped. -* -* If a function only works on lists then it is not included. -**/ -interface UnderscoreStringOOPWrapper { - /************** - * Collections * - ***************/ - - // There are no Collection OOP wrappers for String - - /********* - * Arrays * - **********/ - - // There are no Array OOP wrappers for String - - /************ - * Functions * - *************/ - - // There are no Function OOP wrappers for String - - /********** - * Objects * - ***********/ - - // These don't seem entirely useful since it is known to be a string - // but I have included them since they are all generic on "objects". - - /** - * Returns true if object is a DOM element. - **/ - isElement(): bool; - - /** - * Returns true if object is an Array. - **/ - isArray(): bool; - - /** - * Returns true if value is an any. Note that JavaScript arrays and functions are objects, - * while (normal) strings and numbers are not. - **/ - isObject(): bool; - - /** - * Returns true if object is an Arguments object. - **/ - isArguments(): bool; - - /** - * Returns true if object is a Function. - **/ - isFunction(): bool; - - /** - * Returns true if object is a String. - **/ - isString(): bool; - - /** - * Returns true if object is a Number (including NaN). - **/ - isNumber(): bool; - - /** - * Returns true if object is a finite Number. - **/ - isFinite(): bool; - - /** - * Returns true if object is either true or false. - **/ - isBoolean(): bool; - - /** - * Returns true if object is a Date. - **/ - isDate(): bool; - - /** - * Returns true if object is a RegExp. - **/ - isRegExp(): bool; - - /** - * 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. - **/ - isNaN(): bool; - - /** - * Returns true if the value of object is null. - **/ - isNull(): bool; - - /** - * Returns true if value is undefined. - **/ - isUndefined(): bool; - - /********** - * Utility * - ***********/ - - /** - * 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. - **/ - identity(): string; - - - /** - * 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. Without prefix, returns an integer. - **/ - uniqueId(): string; - - /** - * Escapes a string for insertion into HTML, replacing &, <, >, ", ', and / characters. - **/ - escape(): string; - - /** - * 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 - * <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %> When - * you evaluate a template function, pass in a data object that has properties corresponding to - * the template's free variables. If you're writing a one-off, you can pass the data object as - * the second parameter to template in order to render immediately instead of returning a template - * function. The settings argument should be a hash containing any _.templateSettings that should - * be overridden. - **/ - template(data?: any, settings?: UnderscoreTemplateSettings): any; - - /*********** - * Chaining * - ************/ - - // There are no Chaining OOP wrappers for String - - /** - * Extracts the value of a wrapped object. - **/ - value(): string; - - /************** - * OOP Wrapper * - **************/ - - // There are no base OOP Wrappers for String -} - -interface UnderscoreStringArrayOOPWrapper { - - /************** - * Collections * - ***************/ - - /** - * 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. - **/ - each( - iterator: (element: string, index?: number, list?: string[]) => any, - context?: any): void; - - /** - * Alias for 'each'. - **/ - forEach( - iterator: (element: string, index?: number, list?: string[]) => any, - context?: any): void; - - /** - * 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). - **/ - map( - iterator: (element: string, index?: number, list?: string[]) => string, - context?: any): string[]; - - /** - * Alias for 'map'. - **/ - collect( - iterator: (element: string, index?: number, list?: string[]) => string, - context?: any): string[]; - - /** - * 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. The iterator is passed four arguments: the memo, then the value - * and index (or key) of the iteration, and finally a reference to the entire list. - **/ - reduce( - iterator: (memo: string, element: string, index?: number, list?: string[]) => string, - memo: string, - context?: any): string; - - /** - * Alias for 'reduce'. - **/ - inject( - iterator: (memo: string, element: string, index?: number, list?: string[]) => string, - memo: string, - context?: any): string; - - /** - * Alias for 'reduce'. - **/ - foldl( - iterator: (memo: string, element: string, index?: number, list?: string[]) => string, - memo: string, - context?: any): string; - - /** - * 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. - **/ - reduceRight( - iterator: (memo: string, element: string, index?: number, list?: string[]) => string, - memo: string, - context?: any): string; - - /** - * Alias for 'reduceRight'. - **/ - foldr( - iterator: (memo: string, element: string, index?: number, list?: string[]) => string, - memo: string, - context?: any): string; - - /** - * 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. - **/ - find( - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): string; - - /** - * Alias for 'find'. - **/ - detect( - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): string; - - - /** - * 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( - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): string[]; - - /** - * Alias for 'filter'. - **/ - select( - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): string[]; - - - /** - * Returns the values in list without the elements that the truth test (iterator) passes. - * The opposite of filter. - **/ - reject( - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): string[]; - - /** - * Returns true if all of the values in the list pass the iterator truth test. Delegates to the - * native method every, if present. - **/ - all( - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): bool; - - /** - * Alias for 'all'. - **/ - every( - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): bool; - - /** - * 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. - **/ - any( - iterator?: (element: string, index?: number, list?: string[]) => bool, - context?: any): bool; - - /** - * Alias for 'any'. - **/ - some( - iterator: (element: string, index?: number, list?: string[]) => bool, - context?: any): bool; - - /** - * Returns true if the value is present in the list. Uses indexOf internally, - * if list is an Array. - **/ - contains(value: string): bool; - - /** - * Alias for 'contains'. - **/ - include(value: string): bool; - - /** - * 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. - **/ - invoke(methodName: string, ...arguments: any[]): void; - - - /** - * Returns a sorted copy of list, ranked in ascending order by the results of running each value - * through iterator. Iterator may also be the string name of the property to sort by (eg. length). - **/ - sortBy( - iterator: (element: string, index?: number, list?: string[]) => number, - context?: any): string[]; - sortBy(iterator: string, context?: any): string[]; - - /** - * Splits a collection into sets, grouped by the result of running each value through iterator. - * If iterator is a string instead of a function, groups by the property named by iterator on - * each of the values. - **/ - groupBy( - iterator: (element: string, index?: number, list?: string[]) => string, - context?: any): { [key: string]: string[]; }; - groupBy(iterator: string, context?: any): { [key: string]: string[]; }; - - /** - * Sorts a list into groups and returns a count for the number of objects in each group. Similar - * to groupBy, but instead of returning a list of values, returns a count for the number of values - * in that group. - **/ - countBy( - iterator: (element: string, index?: number, list?: string[]) => string, - context?: any): { [key: string]: number; }; - countBy(iterator: string, context?: any): { [key: string]: number; }; - - /** - * Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle. - **/ - shuffle(): string[]; - - /** - * Converts the list (anything that can be iterated over), into a real Array. Useful for transmuting - * the arguments object. - **/ - toArray(): string[]; - - /** - * Return the number of values in the list. - **/ - size(): number; - - /********* - * Arrays * - **********/ - - /** - * Returns the first element of an array. Passing n will return the first n elements of the array. - **/ - first(): string; - first(n: number): string[]; - - /** - * Alias for 'first'. - **/ - head(): string; - head(n: number): string[]; - - /** - * Alias for 'first'. - **/ - take(): string; - take(n: number): string[]; - - /** - * Returns everything but the last entry of the array. Especially useful on the arguments object. - * Pass n to exclude the last n elements from the result. - **/ - initial(n?: number): string[]; - - /** - * Returns the last element of an array. Passing n will return the last n elements of the array. - **/ - last(): string; - last(n: number): string[]; - - /** - * Returns the rest of the elements in an array. Pass an index to return the values of the array - * from that index onward. - **/ - rest(index?: number): string[]; - - /** - * Alias for 'rest'. - **/ - tail(index?: number): string[]; - - /** - * Alias for 'rest'. - **/ - drop(index?: number): string[]; - - /** - * Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", - * undefined and NaN are all falsy. - **/ - compact(): string[]; - - /** - * Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will - * only be flattened a single level. - **/ - flatten(shallow?: bool): string[]; - - /** - * Returns a copy of the array with all instances of the values removed. - **/ - without(...values: string[]): string[]; - - /** - * Computes the union of the passed-in arrays: the list of unique items, in order, that are - * present in one or more of the arrays. - **/ - union(...arrays: string[][]): string[]; - - /** - * 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. - **/ - intersection(...arrays: string[][]): string[]; - - /** - * Similar to without, but returns the values from array that are not present in the other arrays. - **/ - difference(...others: string[]): string[]; - - /** - * 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. If - * you want to compute unique items based on a transformation, pass an iterator function. - **/ - uniq(isSorted?: bool, iterator?: (element: string, index?: number, list?: string[]) => string): string[]; - - /** - * Alias for 'uniq'. - **/ - unique(isSorted?: bool, iterator?: (element: string, index?: number, list?: string[]) => string): string[]; - - /** - * 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. - * If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion. - **/ - zip(...arrays: string[][]): string[][]; - - /** - * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a - * list of keys, and a list of values. - **/ - object(values: any[]): any; - - /** - * 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 ... or, pass a number - * as the third argument in order to look for the first matching value in the array after the given index. - **/ - indexOf(value: string, isSorted?: bool): number; - - /** - * 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. Pass fromIndex to start your search at a given index. - **/ - lastIndexOf(value: string, from?: number): number; - - /** - * 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, including the value you pass. - **/ - sortedIndex(value: string, iterator?: (element: string) => number): number; - - /************ - * Functions * - *************/ - - // There are no Function OOP Wrappers for String[] - - /********** - * Objects * - ***********/ - - /** - * Create a shallow-copied clone of the object. - * Any nested objects or arrays will be copied by reference, not duplicated. - **/ - clone(): string[]; - - /** - * Returns true if object contains no values. - **/ - isEmpty(): bool; - - /** - * Returns true if object is a DOM element. - **/ - isElement(): bool; - - /** - * Returns true if object is an Array. - **/ - isArray(): bool; - - /** - * Returns true if value is an any. Note that JavaScript arrays and functions are objects, - * while (normal) strings and numbers are not. - **/ - isObject(): bool; - - /** - * Returns true if object is an Arguments object. - **/ - isArguments(): bool; - - /** - * Returns true if object is a Function. - **/ - isFunction(): bool; - - /** - * Returns true if object is a String. - **/ - isString(): bool; - - /** - * Returns true if object is a Number (including NaN). - **/ - isNumber(): bool; - - /** - * Returns true if object is a finite Number. - **/ - isFinite(): bool; - - /** - * Returns true if object is either true or false. - **/ - isBoolean(): bool; - - /** - * Returns true if object is a Date. - **/ - isDate(): bool; - - /** - * Returns true if object is a RegExp. - **/ - isRegExp(): bool; - - /** - * 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. - **/ - isNaN(): bool; - - /** - * Returns true if the value of object is null. - **/ - isNull(): bool; - - /** - * Returns true if value is undefined. - **/ - isUndefined(): bool; - - /********** - * Utility * - ***********/ - - /** - * 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. - **/ - identity(value: string[]): string[]; - - /*********** - * Chaining * - ************/ - - /** - * Extracts the value of a wrapped object. - **/ - value(): string[]; - - /************** - * OOP Wrapper * - **************/ - - // There are no base OOP Wrappers for String[] -} - -interface UnderscoreNumberOOPWrapper { - - /************** - * Collections * - ***************/ - - // There are no Collection OOP Wrappers for Number - - /********* - * Arrays * - **********/ - - /** - * 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. - **/ - // start is the OOP wrapped object - range(stop: number, step?: number): number[]; - // stop is the OOP wrapped object, cannot have step provided in this case. - range(): number[]; - - /************ - * Functions * - *************/ - - /** - * Creates a version of the function that will only be run after first being called count times. Useful - * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, - * before proceeding. - **/ - after(fn: Function): Function; - - /********** - * Objects * - ***********/ - - /** - * Returns true if object is a DOM element. - **/ - isElement(): bool; - - /** - * Returns true if object is an Array. - **/ - isArray(): bool; - - /** - * Returns true if value is an any. Note that JavaScript arrays and functions are objects, - * while (normal) strings and numbers are not. - **/ - isObject(): bool; - - /** - * Returns true if object is an Arguments object. - **/ - isArguments(): bool; - - /** - * Returns true if object is a Function. - **/ - isFunction(): bool; - - /** - * Returns true if object is a String. - **/ - isString(): bool; - - /** - * Returns true if object is a Number (including NaN). - **/ - isNumber(): bool; - - /** - * Returns true if object is a finite Number. - **/ - isFinite(): bool; - - /** - * Returns true if object is either true or false. - **/ - isBoolean(): bool; - - /** - * Returns true if object is a Date. - **/ - isDate(): bool; - - /** - * Returns true if object is a RegExp. - **/ - isRegExp(): bool; - - /** - * 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. - **/ - isNaN(): bool; - - /** - * Returns true if the value of object is null. - **/ - isNull(): bool; - - /** - * Returns true if value is undefined. - **/ - isUndefined(): bool; - - /********** - * Utility * - ***********/ - - /** - * 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. - **/ - identity(value: number): number; - - /** - * Invokes the given iterator function n times. - * Each invocation of iterator is called with an index argument. - * @example - * - * _(3).times(function(n){ genie.grantWishNumber(n); }); - * - **/ - times(iterator: (n: number) => void , context?: any): void; - - /** - * Returns a random integer between min and max, inclusive. If you only pass one argument, - * it will return a number between 0 and that number. - **/ - // max is OOP wrapped - random(): number; - // min is OOP wrapped - random(max: number): number; - - /*********** - * Chaining * - ************/ - - /** - * Extracts the value of a wrapped object. - **/ - value(): number; - - /************** - * OOP Wrapper * - **************/ - - // There are no base OOP Wrappers for Number -} - -interface UnderscoreNumberArrayOOPWrapper { - - /************** - * Collections * - ***************/ - - /** - * 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. - **/ - each( - iterator: (element: number, index?: number, list?: number[]) => any, - context?: any): void; - - /** - * Alias for 'each'. - **/ - forEach( - iterator: (element: number, index?: number, list?: number[]) => any, - context?: any): void; - - /** - * 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). - **/ - map( - iterator: (element: number, index?: number, list?: number[]) => number, - context?: any): number[]; - - /** - * Alias for 'map'. - **/ - collect( - iterator: (element: number, index?: number, list?: number[]) => number, - context?: any): number[]; - - /** - * 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. The iterator is passed four arguments: the memo, then the value - * and index (or key) of the iteration, and finally a reference to the entire list. - **/ - reduce( - iterator: (memo: number, element: number, index?: number, list?: number[]) => number, - memo: number, - context?: any): number; - - /** - * Alias for 'reduce'. - **/ - inject( - iterator: (memo: number, element: number, index?: number, list?: number[]) => number, - memo: number, - context?: any): number; - - /** - * Alias for 'reduce'. - **/ - foldl( - iterator: (memo: number, element: number, index?: number, list?: number[]) => number, - memo: number, - context?: any): number; - - /** - * 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. - **/ - reduceRight( - iterator: (memo: number, element: number, index?: number, list?: number[]) => number, - memo: number, - context?: any): number; - - /** - * Alias for 'reduceRight'. - **/ - foldr( - iterator: (memo: number, element: number, index?: number, list?: number[]) => number, - memo: number, - context?: any): number; - - /** - * 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. - **/ - find( - iterator: (element: number, index?: number, list?: number[]) => bool, - context?: any): number; - - /** - * Alias for 'find'. - **/ - detect( - iterator: (element: number, index?: number, list?: number[]) => bool, - context?: any): number; - - - /** - * 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( - iterator: (element: number, index?: number, list?: number[]) => bool, - context?: any): number[]; - - /** - * Alias for 'filter'. - **/ - select( - iterator: (element: number, index?: number, list?: number[]) => bool, - context?: any): number[]; - - /** - * Returns the values in list without the elements that the truth test (iterator) passes. - * The opposite of filter. - **/ - reject( - iterator: (element: number, index?: number, list?: number[]) => bool, - context?: any): number[]; - - /** - * Returns true if all of the values in the list pass the iterator truth test. Delegates to the - * native method every, if present. - **/ - all( - iterator: (element: number, index?: number, list?: string[]) => bool, - context?: any): bool; - - /** - * Alias for 'all'. - **/ - every( - iterator: (element: number, index?: number, list?: string[]) => bool, - context?: any): bool; - - /** - * 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. - **/ - any( - iterator?: (element: number, index?: number, list?: string[]) => bool, - context?: any): bool; - - /** - * Alias for 'any'. - **/ - some( - iterator: (element: number, index?: number, list?: string[]) => bool, - context?: any): bool; - - /** - * Returns true if the value is present in the list. Uses indexOf internally, - * if list is an Array. - **/ - contains(value: number): bool; - - /** - * Alias for 'contains'. - **/ - include(value: number): bool; - - /** - * 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. - **/ - invoke(methodName: string, ...arguments: any[]): void; - - /** - * 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. - **/ - max(): number; - - /** - * 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. - **/ - min(): number; - - /** - * Returns a sorted copy of list, ranked in ascending order by the results of running each value - * through iterator. Iterator may also be the string name of the property to sort by (eg. length). - **/ - sortBy( - iterator: (element: number, index?: number, list?: number[]) => number, - context?: any): number[]; - sortBy(iterator: string, context?: any): number[]; - - /** - * Splits a collection into sets, grouped by the result of running each value through iterator. - * If iterator is a string instead of a function, groups by the property named by iterator on - * each of the values. - **/ - groupBy( - iterator: (element: number, index?: number, list?: number[]) => string, - context?: any): { [key: string]: number[]; }; - groupBy(iterator: string, context?: any): { [key: string]: number[]; }; - - /** - * Sorts a list into groups and returns a count for the number of objects in each group. Similar - * to groupBy, but instead of returning a list of values, returns a count for the number of values - * in that group. - **/ - countBy( - iterator: (element: number, index?: number, list?: number[]) => string, - context?: any): { [key: string]: number; }; - countBy(iterator: string, context?: any): { [key: string]: number; }; - - /** - * Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle. - **/ - shuffle(): number[]; - - /** - * Converts the list (anything that can be iterated over), into a real Array. Useful for transmuting - * the arguments object. - **/ - toArray(): number[]; - - /** - * Return the number of values in the list. - **/ - size(): number; - - /********* - * Arrays * - **********/ - - /** - * Returns the first element of an array. Passing n will return the first n elements of the array. - **/ - first(): number; - first(n: number): number[]; - - /** - * Alias for 'first'. - **/ - head(): number; - head(n: number): number[]; - - /** - * Alias for 'first'. - **/ - take(): number; - take(n: number): number[]; - - /** - * Returns everything but the last entry of the array. Especially useful on the arguments object. - * Pass n to exclude the last n elements from the result. - **/ - initial(n?: number): number[]; - - /** - * Returns the last element of an array. Passing n will return the last n elements of the array. - **/ - last(): number; - last(n: number): number[]; - - /** - * Returns the rest of the elements in an array. Pass an index to return the values of the array - * from that index onward. - **/ - rest(index?: number): number[]; - - /** - * Alias for 'rest'. - **/ - tail(index?: number): number[]; - - /** - * Alias for 'rest'. - **/ - drop(index?: number): number[]; - - /** - * Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", - * undefined and NaN are all falsy. - **/ - compact(): number[]; - - /** - * Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will - * only be flattened a single level. - **/ - flatten(shallow?: bool): number[]; - - /** - * Returns a copy of the array with all instances of the values removed. - **/ - without(...values: number[]): number[]; - - /** - * Computes the union of the passed-in arrays: the list of unique items, in order, that are - * present in one or more of the arrays. - **/ - union(...arrays: number[][]): number[]; - - /** - * 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. - **/ - intersection(...arrays: number[][]): number[]; - - /** - * Similar to without, but returns the values from array that are not present in the other arrays. - **/ - difference(...others: number[]): number[]; - - /** - * 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. If - * you want to compute unique items based on a transformation, pass an iterator function. - **/ - uniq(isSorted?: bool, iterator?: (element: number, index?: number, list?: number[]) => number): number[]; - - /** - * Alias for 'uniq'. - **/ - unique(isSorted?: bool, iterator?: (element: number, index?: number, list?: number[]) => number): number[]; - - /** - * 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. - * If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion. - **/ - zip(...arrays: number[][]): number[][]; - - /** - * 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 ... or, pass a number - * as the third argument in order to look for the first matching value in the array after the given index. - **/ - indexOf(value: number, isSorted?: bool): number; - - /** - * 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. Pass fromIndex to start your search at a given index. - **/ - lastIndexOf(value: number, from?: number): number; - - /** - * 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, including the value you pass. - **/ - sortedIndex(value: number, iterator?: (element: number) => number): number; - - /************ - * Functions * - *************/ - - // There are no Function OOP Wrappers for Number[] - - /********** - * Objects * - ***********/ - - /** - * Create a shallow-copied clone of the object. - * Any nested objects or arrays will be copied by reference, not duplicated. - **/ - clone(): number[]; - - /** - * Returns true if object contains no values. - **/ - isEmpty(): bool; - - /** - * Returns true if object is a DOM element. - **/ - isElement(): bool; - - /** - * Returns true if object is an Array. - **/ - isArray(): bool; - - /** - * Returns true if value is an any. Note that JavaScript arrays and functions are objects, - * while (normal) strings and numbers are not. - **/ - isObject(): bool; - - /** - * Returns true if object is an Arguments object. - **/ - isArguments(): bool; - - /** - * Returns true if object is a Function. - **/ - isFunction(): bool; - - /** - * Returns true if object is a String. - **/ - isString(): bool; - - /** - * Returns true if object is a Number (including NaN). - **/ - isNumber(): bool; - - /** - * Returns true if object is a finite Number. - **/ - isFinite(): bool; - - /** - * Returns true if object is either true or false. - **/ - isBoolean(): bool; - - /** - * Returns true if object is a Date. - **/ - isDate(): bool; - - /** - * Returns true if object is a RegExp. - **/ - isRegExp(): bool; - - /** - * 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. - **/ - isNaN(): bool; - - /** - * Returns true if the value of object is null. - **/ - isNull(): bool; - - /** - * Returns true if value is undefined. - **/ - isUndefined(): bool; - - /********** - * Utility * - ***********/ - - /** - * 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. - **/ - identity(): number[]; - - /*********** - * Chaining * - ************/ - - /** - * Extracts the value of a wrapped object. - **/ - value(): number[]; - - /************** - * OOP Wrapper * - **************/ - - // There are no base OOP Wrappers for Number[] -} - -interface UnderscoreObjectOOPWrapper { - - /************** - * Collections * - ***************/ - - /** - * 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. - **/ - each( - iterator: (value: any, key?: string, object?: any) => any, - context?: any): void; - - /** - * Alias for 'each'. - **/ - forEach( - iterator: (value: any, key?: string, object?: any) => any, - context?: any): void; - - /** - * 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). - **/ - map( - iterator: (value: any, key?: string, object?: any) => any, - context?: any): any[]; - - /** - * Alias for 'map'. - **/ - collect( - iterator: (value: any, key?: string, object?: any) => any, - context?: any): any[]; - - /********* - * Arrays * - **********/ - - // There are no Array OOP Wrappers for any - - /************ - * Functions * - *************/ - - /** - * 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. - **/ - bindAll(...methodNames: string[]): void; - - /********** - * Objects * - ***********/ - - /** - * Retrieve all the names of the object's properties. - **/ - keys(): string[]; - - /** - * Return all of the values of the object's properties. - **/ - values(): any[]; - - /** - * Convert an object into a list of [key, value] pairs. - **/ - pairs(): any[][]; - - /** - * Returns a copy of the object where the keys have become the values and the values the keys. - * For this to work, all of your object's values should be unique and string serializable. - **/ - invert(): any; - - /** - * 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. - **/ - functions(): string[]; - - /** - * Copy all of the properties in the source objects over to the destination object, and return - * the destination object. It's in-order, so the last source will override properties of the - * same name in previous arguments. - **/ - extend(...sources: any[]): any; - - /** - * Return a copy of the object, filtered to only have values for the whitelisted keys - * (or array of valid keys). - **/ - pick(...keys: string[]): any; - - /** - * Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). - **/ - omit(...keys: string[]): any; - - /** - * Fill in null and undefined properties in object with values from the defaults objects, - * and return the object. As soon as the property is filled, further defaults will have no effect. - **/ - defaults(...defaults: any[]): any; - - /** - * Create a shallow-copied clone of the object. - * Any nested objects or arrays will be copied by reference, not duplicated. - **/ - clone(): any; - - /** - * 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. - **/ - tap(intercepter: Function): any; - - /** - * Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe - * reference to the hasOwnProperty function, in case it's been overridden accidentally. - **/ - has(key: string): bool; - - /** - * Performs an optimized deep comparison between the two objects, - * to determine if they should be considered equal. - **/ - isEqual(other: any): bool; - - /** - * Returns true if object contains no values. - **/ - isEmpty(): bool; - - /** - * Returns true if object is a DOM element. - **/ - isElement(): bool; - - /** - * Returns true if object is an Array. - **/ - isArray(): bool; - - /** - * Returns true if value is an any. Note that JavaScript arrays and functions are objects, - * while (normal) strings and numbers are not. - **/ - isObject(): bool; - - /** - * Returns true if object is an Arguments object. - **/ - isArguments(): bool; - - /** - * Returns true if object is a Function. - **/ - isFunction(): bool; - - /** - * Returns true if object is a String. - **/ - isString(): bool; - - /** - * Returns true if object is a Number (including NaN). - **/ - isNumber(): bool; - - /** - * Returns true if object is a finite Number. - **/ - isFinite(): bool; - - /** - * Returns true if object is either true or false. - **/ - isBoolean(): bool; - - /** - * Returns true if object is a Date. - **/ - isDate(): bool; - - /** - * Returns true if object is a RegExp. - **/ - isRegExp(): bool; - - /** - * 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. - **/ - isNaN(): bool; - - /** - * Returns true if the value of object is null. - **/ - isNull(): bool; - - /** - * Returns true if value is undefined. - **/ - isUndefined(): bool; - - /********** - * Utility * - ***********/ - - /** - * 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. - **/ - identity(value: any): any; - - /** - * 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. - * @example - * - * _.mixin({ - * capitalize : function(string) { - * return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase(); - * } - * }); - * _("fabio").capitalize(); - * => "Fabio" - * - **/ - mixin(): void; - - /** - * If the value of the named property is a function then invoke it; otherwise, return it. - **/ - result(property: string): any; - - /*********** - * Chaining * - ************/ - - /** - * Returns a wrapped object. Calling methods on this object will continue to return wrapped objects - * until value is used. - **/ - chain(): any; - - /** - * Extracts the value of a wrapped object. - **/ - value(): any; - - /************** - * OOP Wrapper * - **************/ - - // There are no base OOP Wrappers for any -} - -interface UnderscoreObjectArrayOOPWrapper { - - /************** - * Collections * - ***************/ - - /** - * 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. - **/ - each( - iterator: (element: any, index?: number, list?: any[]) => any, - context?: any): void; - - /** - * Alias for 'each'. - **/ - forEach( - iterator: (element: any, index?: number, list?: any[]) => any, - context?: any): void; - - /** - * 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). - **/ - map( - iterator: (element: any, index?: number, list?: any[]) => any, - context?: any): any[]; - - /** - * Alias for 'map'. - **/ - collect( - iterator: (element: any, index?: number, list?: any[]) => any, - context?: any): any[]; - - /** - * 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. The iterator is passed four arguments: the memo, then the value - * and index (or key) of the iteration, and finally a reference to the entire list. - **/ - reduce( - iterator: (memo: any, element: any, index?: number, list?: any[]) => any, - memo: any, - context?: any): any; - - /** - * Alias for 'reduce'. - **/ - inject( - iterator: (memo: any, element: any, index?: number, list?: any[]) => any, - memo: any, - context?: any): any; - - /** - * Alias for 'reduce'. - **/ - foldl( - iterator: (memo: any, element: any, index?: number, list?: any[]) => any, - memo: any, - context?: any): any; - - /** - * 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. - **/ - reduceRight( - iterator: (memo: any, element: any, index?: number, list?: any[]) => any, - memo: any, - context?: any): any; - - /** - * Alias for 'reduceRight'. - **/ - foldr( - iterator: (memo: any, element: any, index?: number, list?: any[]) => any, - memo: any, - context?: any): any; - - /** - * 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. - **/ - find( - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): any; - - /** - * Alias for 'find'. - **/ - detect( - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): any; - - - /** - * 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( - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): any[]; - - /** - * Alias for 'filter'. - **/ - select( - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): any[]; - - /** - * Looks through each value in the list, returning an array of all the values that contain all - * of the key-value pairs listed in properties. - **/ - where(properties: any): any[]; - - /** - * Returns the values in list without the elements that the truth test (iterator) passes. - * The opposite of filter. - **/ - reject( - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): any[]; - - /** - * Returns true if all of the values in the list pass the iterator truth test. Delegates to the - * native method every, if present. - **/ - all( - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): bool; - - /** - * Alias for 'all'. - **/ - every( - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): bool; - - /** - * 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. - **/ - any( - iterator?: (element: any, index?: number, list?: any[]) => bool, - context?: any): bool; - - /** - * Alias for 'any'. - **/ - some( - iterator: (element: any, index?: number, list?: any[]) => bool, - context?: any): bool; - - /** - * Returns true if the value is present in the list. Uses indexOf internally, - * if list is an Array. - **/ - contains(value: any): bool; - - /** - * Alias for 'contains'. - **/ - include(value: any): bool; - - /** - * 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. - **/ - invoke(methodName: string, ...arguments: any[]): void; - - /** - * A convenient version of what is perhaps the most common use-case for map: extracting a list of - * property values. - **/ - pluck(propertyName: string): any[]; - - /** - * 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. - **/ - max( - iterator: (element: any, index?: number, list?: any[]) => number, - context?: any): any; - - /** - * 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. - **/ - min( - iterator: (obj: any, index?: number, list?: any[]) => number, - context?: any): any; - - /** - * Returns a sorted copy of list, ranked in ascending order by the results of running each value - * through iterator. Iterator may also be the string name of the property to sort by (eg. length). - **/ - sortBy( - iterator: (element: any, index?: number, list?: any[]) => number, - context?: any): any[]; - sortBy(iterator: string, context?: any): any[]; - - /** - * Splits a collection into sets, grouped by the result of running each value through iterator. - * If iterator is a string instead of a function, groups by the property named by iterator on - * each of the values. - **/ - groupBy( - iterator: (element: any, index?: number, list?: any[]) => string, - context?: any): { [key: string]: any[]; }; - groupBy(iterator: string, context?: any): { [key: string]: any[]; }; - - /** - * Sorts a list into groups and returns a count for the number of objects in each group. Similar - * to groupBy, but instead of returning a list of values, returns a count for the number of values - * in that group. - **/ - countBy( - iterator: (element: any, index?: number, list?: any[]) => string, - context?: any): { [key: string]: number; }; - countBy(iterator: string, context?: any): { [key: string]: number; }; - - /** - * Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle. - **/ - shuffle(): any[]; - - /** - * Converts the list (anything that can be iterated over), into a real Array. Useful for transmuting - * the arguments object. - **/ - toArray(): any[]; - - /** - * Return the number of values in the list. - **/ - size(): number; - - /********* - * Arrays * - **********/ - - /** - * Returns the first element of an array. Passing n will return the first n elements of the array. - **/ - first(): any; - first(n: number): any[]; - - /** - * Alias for 'first'. - **/ - head(): any; - head(n: number): any[]; - - /** - * Alias for 'first'. - **/ - take(): any; - take(n: number): any[]; - - /** - * Returns everything but the last entry of the array. Especially useful on the arguments object. - * Pass n to exclude the last n elements from the result. - **/ - initial(n?: number): any[]; - - /** - * Returns the last element of an array. Passing n will return the last n elements of the array. - **/ - last(): any; - last(n: number): any[]; - - /** - * Returns the rest of the elements in an array. Pass an index to return the values of the array - * from that index onward. - **/ - rest(index?: number): any[]; - - /** - * Alias for 'rest'. - **/ - tail(index?: number): any[]; - - /** - * Alias for 'rest'. - **/ - drop(index?: number): any[]; - - /** - * Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", - * undefined and NaN are all falsy. - **/ - compact(): any[]; - - /** - * Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will - * only be flattened a single level. - **/ - flatten(shallow?: bool): any[]; - - /** - * Returns a copy of the array with all instances of the values removed. - **/ - without(...values: any[]): any[]; - - /** - * Computes the union of the passed-in arrays: the list of unique items, in order, that are - * present in one or more of the arrays. - **/ - union(...arrays: any[][]): any[]; - - /** - * 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. - **/ - intersection(...arrays: any[][]): any[]; - - /** - * Similar to without, but returns the values from array that are not present in the other arrays. - **/ - difference(...others: any[]): any[]; - - /** - * 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. If - * you want to compute unique items based on a transformation, pass an iterator function. - **/ - uniq(isSorted?: bool, iterator?: (element: any, index?: number, list?: any[]) => any): any[]; - - /** - * Alias for 'uniq'. - **/ - unique(isSorted?: bool, iterator?: (element: any, index?: number, list?: any[]) => any): any[]; - - /** - * 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. - * If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion. - **/ - zip(...arrays: any[][]): any[][]; - - /** - * 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 ... or, pass a number - * as the third argument in order to look for the first matching value in the array after the given index. - **/ - indexOf(value: any, isSorted?: bool): number; - - /** - * 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. Pass fromIndex to start your search at a given index. - **/ - lastIndexOf(value: any, from?: number): number; - - /** - * 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, including the value you pass. - **/ - sortedIndex(value: any, iterator?: (element: any) => number): number; - - /************ - * Functions * - *************/ - - // There are no Function OOP Wrappers for any[] - - /********** - * Objects * - ***********/ - - /** - * Create a shallow-copied clone of the object. - * Any nested objects or arrays will be copied by reference, not duplicated. - **/ - clone(list: any[]): any[]; - - /** - * Returns true if object contains no values. - **/ - isEmpty(): bool; - - /** - * Returns true if object is a DOM element. - **/ - isElement(): bool; - - /** - * Returns true if object is an Array. - **/ - isArray(): bool; - - /** - * Returns true if value is an any. Note that JavaScript arrays and functions are objects, - * while (normal) strings and numbers are not. - **/ - isObject(): bool; - - /** - * Returns true if object is an Arguments object. - **/ - isArguments(): bool; - - /** - * Returns true if object is a Function. - **/ - isFunction(): bool; - - /** - * Returns true if object is a String. - **/ - isString(): bool; - - /** - * Returns true if object is a Number (including NaN). - **/ - isNumber(): bool; - - /** - * Returns true if object is a finite Number. - **/ - isFinite(): bool; - - /** - * Returns true if object is either true or false. - **/ - isBoolean(): bool; - - /** - * Returns true if object is a Date. - **/ - isDate(): bool; - - /** - * Returns true if object is a RegExp. - **/ - isRegExp(): bool; - - /** - * 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. - **/ - isNaN(): bool; - - /** - * Returns true if the value of object is null. - **/ - isNull(): bool; - - /** - * Returns true if value is undefined. - **/ - isUndefined(): bool; - - /********** - * Utility * - ***********/ - - /** - * 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. - **/ - identity(): any[]; - - /*********** - * Chaining * - ************/ - - /** - * Returns a wrapped object. Calling methods on this object will continue to return wrapped objects - * until value is used. - **/ - chain(): any; - - /** - * Extracts the value of a wrapped object. - **/ - value(): any[]; - - /************** - * OOP Wrapper * - **************/ - - // There are no base OOP Wrappers for any[] -} - - -declare var _: Underscore; +/* +underscore-1.4.4.d.ts may be freely distributed under the MIT license. + +Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/underscore.d.ts + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*/ + +interface Underscore { + + /************** + * Collections * + **************/ + + /** + * 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, object). Delegates to the native forEach function if it exists. + * @param list Iterates over this list of elements. + * @param iterator Iterator function for each element `list`. + * @param context 'this' object in `iterator`, optional. + **/ + each( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * 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, object). Delegates to the native forEach function if it exists. + * @param obj Iterators over this object's properties. + * @param iterator Iterator function for each property on `obj`. + * @param context `this` object in the `iterator`, optional. + **/ + each( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * Alias for 'each'. + * @see each + **/ + forEach( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * Alias for 'each'. + * @see each + **/ + forEach( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * 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, object). + * @param list Maps the elements of this array. + * @param iterator Map iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The mapped array result. + **/ + map( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * 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, object). + * @param list Maps the properties of this object. + * @param iterator Map iterator function for each property on `obj`. + * @param context `this` object in `iterator`, optional. + * @return The mapped object result. + **/ + map( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * Alias for 'map'. + * @see map + **/ + collect( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Alias for 'map'. + * @see map + **/ + collect( + obj: Object, + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * 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. The iterator is passed four arguments: the memo, then the value + * and index (or key) of the iteration, and finally a reference to the entire list. + * @param list Reduces the elements of this array. + * @param iterator Reduce iterator function for each element in `list`. + * @param memo Initial reduce state. + * @param context `this` object in `iterator`, optional. + * @return Reduced object result. + **/ + reduce( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + inject( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + foldl( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * 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. + * @param list Reduces the elements of this array. + * @param iterator Reduce iterator function for each element in `list`. + * @param memo Initial reduce state. + * @param context `this` object in `iterator`, optional. + * @return Reduced object result. + **/ + reduceRight( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduceRight'. + * @see reduceRight + **/ + foldr( + list: any[], + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * 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. + * @param list Searches for a value in this list. + * @param iterator Search iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The first acceptable found element in `list`, if nothing is found undefined/null is returned. + **/ + find( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + /** + * Alias for 'find'. + * @see find + **/ + detect( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + + /** + * 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. + * @param list Filter elements out of this list. + * @param iterator Filter iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The filtered list of elements. + **/ + filter( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Alias for 'filter'. + * @see filter + **/ + select( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Looks through each value in the list, returning an array of all the values that contain all + * of the key-value pairs listed in properties. + * @param list List to match elements again `properties`. + * @param properties The properties to check for on each element within `list`. + * @return The elements within `list` that contain the required `properties`. + **/ + where(list: any[], properties: any): any[]; + + /** + * Looks through the list and returns the first value that matches all of the key-value pairs listed in properties. + * @param list Search through this list's elements for the first object with all `properties`. + * @param properties Properties to look for on the elements within `list`. + * @return The first element in `list` that has all `properties`. + **/ + findWhere(list: any[], properties: any): any; + + /** + * Returns the values in list without the elements that the truth test (iterator) passes. + * The opposite of filter. + * Return all the elements for which a truth test fails. + * @param list Reject elements within this list. + * @param iterator Reject iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The rejected list of elements. + **/ + reject( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Returns true if all of the values in the list pass the iterator truth test. Delegates to the + * native method every, if present. + * @param list Truth test against all elements within this list. + * @param iterator Trust test iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return True if all elements passed the truth test, otherwise false. + **/ + all( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'all'. + * @see all + **/ + every( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * 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. + * @param list Truth test against all elements within this list. + * @param iterator Trust test iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return True if any elements passed the truth test, otherwise false. + **/ + any( + list: any[], + iterator?: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'any'. + * @see any + **/ + some( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Returns true if the value is present in the list. Uses indexOf internally, + * if list is an Array. + * @param list Checks each element to see if `value` is present. + * @param value The value to check for within `list`. + * @return True if `value` is present in `list`, otherwise false. + **/ + contains(list: any[], value: any): bool; + + /** + * Alias for 'contains'. + * @see contains + **/ + include(list: any[], value: any): bool; + + /** + * 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. + * @param list The element's in this list will each have the method `methodName` invoked. + * @param methodName The method's name to call on each element within `list`. + * @param arguments Additional arguments to pass to the method `methodName`. + **/ + invoke(list: any[], methodName: string, ...arguments: any[]): void; + + /** + * A convenient version of what is perhaps the most common use-case for map: extracting a list of + * property values. + * @param list The list to pluck elements out of that have the property `propertyName`. + * @param propertyName The property to look for on each element within `list`. + * @return The list of elements within `list` that have the property `propertyName`. + **/ + pluck(list: any[], propertyName: string): any[]; + + /** + * Returns the maximum value in list. + * @param list Finds the maximum value in this list. + * @return Maximum value in `list`. + **/ + max(list: number[]): number; + /** + * 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. + * @param list Finds the maximum value in this list. + * @param iterator Compares each element in `list` to find the maximum value. + * @param context `this` object in `iterator`, optional. + * @return The maximum element within `list`. + **/ + max( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Returns the minimum value in list. + * @param list Finds the minimum value in this list. + * @return Minimum value in `list`. + **/ + min(list: number[]): number; + /** + * 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. + * @param list Finds the minimum value in this list. + * @param iterator Compares each element in `list` to find the minimum value. + * @param context `this` object in `iterator`, optional. + * @return The minimum element within `list`. + **/ + min( + list: any[], + iterator: (obj: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Returns a sorted copy of list, ranked in ascending order by the results of running each value + * through iterator. Iterator may also be the string name of the property to sort by (eg. length). + * @param list Sorts this list. + * @param iterator Sort iterator for each element within `list`. + * @param context `this` object in `iterator`, optional. + * @return A sorted copy of `list`. + **/ + sortBy( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Returns a sorted copy of list, ranked in ascending order by the results of running each value + * through iterator. Iterator may also be the string name of the property to sort by (eg. length). + * @param list Sorts this list. + * @param iterator Sort iterator for each element within `list`. + * @param context `this` object in `iterator`, optional. + * @return A sorted copy of `list`. + **/ + sortBy( + list: any[], + iterator: string, + context?: any): any[]; + + /** + * Splits a collection into sets, grouped by the result of running each value through iterator. + * If iterator is a string instead of a function, groups by the property named by iterator on + * each of the values. + * @param list Groups this list. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the grouped elements from `list`. + **/ + groupBy( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: any[]; }; + /** + * Splits a collection into sets, grouped by the result of running each value through iterator. + * If iterator is a string instead of a function, groups by the property named by iterator on + * each of the values. + * @param list Groups this list. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the grouped elements from `list`. + **/ + groupBy( + list: any[], + iterator: string, + context?: any): { [key: string]: any[]; }; + + /** + * Sorts a list into groups and returns a count for the number of objects in each group. Similar + * to groupBy, but instead of returning a list of values, returns a count for the number of values + * in that group. + * @param list Group elements in this list and then count the number of elements in each group. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the number of elements in that group. + **/ + countBy( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: number; }; + /** + * Sorts a list into groups and returns a count for the number of objects in each group. Similar + * to groupBy, but instead of returning a list of values, returns a count for the number of values + * in that group. + * @param list Group elements in this list and then count the number of elements in each group. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the number of elements in that group. + **/ + countBy( + list: any[], + iterator: string, + context?: any): { [key: string]: number; }; + + /** + * Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle. + * @param list List to shuffle. + * @return Shuffled copy of `list`. + **/ + shuffle(list: any[]): any[]; + + /** + * Converts the list (anything that can be iterated over), into a real Array. Useful for transmuting + * the arguments object. + * @param list object to transform into an array. + * @return `list` as an array. + **/ + toArray(list: any): any[]; + + /** + * Return the number of values in the list. + * @param list Count the number of values/elements in this list. + * @return Number of values in `list`. + **/ + size(list: any): number; + + /********* + * Arrays * + **********/ + + /** + * Returns the first element of an array. Passing n will return the first n elements of the array. + * @param array Retrieves the first element of this array. + * @return Returns the first element of `array`. + **/ + first(array: any[]): any; + /** + * Returns the first element of an array. Passing n will return the first n elements of the array. + * @param array Retreives the first `n` elements of this array. + * @param n Return more than one element from `array`. + * @return Returns the first `n` elements from `array. + **/ + first(array: any[], n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + head(array: any[]): any; + /** + * Alias for 'first'. + * @see first + **/ + head(array: any[], n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + take(array: any[]): any; + /** + * Alias for 'first'. + * @see first + **/ + take(array: any[], n: number): any[]; + + /** + * Returns everything but the last entry of the array. Especially useful on the arguments object. + * Pass n to exclude the last n elements from the result. + * @param array Retreive all elements except the last `n`. + * @param n Leaves this many elements behind, optional. + * @return Returns everything but the last `n` elements of `array`. + **/ + initial(array: any[], n?: number): any[]; + + /** + * Returns the last element of an array. Passing n will return the last n elements of the array. + * @param array Retrieves the last element of this array. + * @return Returns the last element of `array`. + **/ + last(array: any[]): any; + /** + * Returns the last element of an array. Passing n will return the last n elements of the array. + * @param array Retreives the last `n` elements of this array. + * @param n Return more than one element from `array`. + * @return Returns the last `n` elements from `array. + **/ + last(array: any[], n: number): any[]; + + /** + * Returns the rest of the elements in an array. Pass an index to return the values of the array + * from that index onward. + * @param array The array to retrieve all but the first `index` elements. + * @param index The index to start retrieving elements forward from, optional, default = 1. + * @return Returns the elements of `array` from `index` to the end of `array`. + **/ + rest(array: any[], index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + tail(array: any[], index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + drop(array: any[], index?: number): any[]; + + /** + * Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", + * undefined and NaN are all falsy. + * @param array Array to compact. + * @return Copy of `array` without false values. + **/ + compact(array: any[]): any[]; + + /** + * Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will + * only be flattened a single level. + * @param array The array to flatten. + * @param shallow If true then only flatten one level, optional, default = false. + * @return `array` flattened. + **/ + flatten(array: any, shallow?: bool): any; + + /** + * Returns a copy of the array with all instances of the values removed. + * @param array The array to remove `values` from. + * @param values The values to remove from `array`. + * @return Copy of `array` without `values`. + **/ + without(array: any[], ...values: any[]): any[]; + + /** + * Computes the union of the passed-in arrays: the list of unique items, in order, that are + * present in one or more of the arrays. + * @param arrays Array of arrays to compute the union of. + * @return The union of elements within `arrays`. + **/ + union(...arrays: any[][]): any[]; + + /** + * 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. + * @param arrays Array of arrays to compute the intersection of. + * @return The intersection of elements within `arrays`. + **/ + intersection(...arrays: any[][]): any[]; + + /** + * Similar to without, but returns the values from array that are not present in the other arrays. + * @param array Keeps values that are within `others`. + * @param others The values to keep within `array`. + * @return Copy of `array` with only `others` values. + **/ + difference(array: any[], ...others: any[]): any[]; + + /** + * 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. If + * you want to compute unique items based on a transformation, pass an iterator function. + * @param array Array to remove duplicates from. + * @param isSorted True if `array` is already sorted, optiona, default = false. + * @param iterator Transform the elements of `array` before comparisons for uniqueness. + * @param context 'this' object in `iterator`, optional. + * @return Copy of `array` where all elements are unique. + **/ + uniq( + array: any[], + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * 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. If + * you want to compute unique items based on a transformation, pass an iterator function. + * @param array Array to remove duplicates from. + * @param iterator Transform the elements of `array` before comparisons for uniqueness. + * @param context 'this' object in `iterator`, optional. + * @return Copy of `array` where all elements are unique. + **/ + uniq( + array: any[], + iterator?: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + + /** + * Alias for 'uniq'. + * @see uniq + **/ + unique(array: any[], + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any): any[]; + + /** + * 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. + * If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion. + * @param arrays The arrays to merge/zip. + * @return Zipped version of `arrays`. + **/ + zip(...arrays: any[][]): any[][]; + + /** + * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a + * list of keys, and a list of values. + * @param keys Key array. + * @param values Value array. + * @return An object containing the `keys` as properties and `values` as the property values. + **/ + object(keys: string[], values: any[]): any; + /** + * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a + * list of keys, and a list of values. + * @param keyValuePairs Array of [key, value] pairs. + * @return An object containing the `keys` as properties and `values` as the property values. + **/ + object(...keyValuePairs: any[][]): any; + + /** + * 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 ... or, pass a number + * as the third argument in order to look for the first matching value in the array after the given index. + * @param array The array to search for the index of `value`. + * @param value The value to search for within `array`. + * @param isSorted True if the array is already sorted, optional, default = false. + * @return The index of `value` within `array`. + **/ + indexOf(array: any[], value: any, isSorted?: bool): number; + + /** + * 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. Pass fromIndex to start your search at a given index. + * @param array The array to search for the last index of `value`. + * @param value The value to search for within `array`. + * @param from The starting index for the search, optional. + * @return The index of the last occurance of `value` within `array`. + **/ + lastIndexOf(array: any[], value: any, from?: number): number; + + /** + * 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, including the value you pass. + * @param list The sorted list. + * @param value The value to determine its index within `list`. + * @param iterator Iterator to compute the sort ranking of each value, optional. + * @return The index where `value` should be inserted into `list`. + **/ + sortedIndex(list: any[], value: any, iterator?: (element: any) => number): number; + + /** + * 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. + * @param start Start here. + * @param stop Stop here. + * @param step The number to count up by each iteration, optional, default = 1. + * @return Array of numbers from `start` to `stop` with increments of `step`. + **/ + range(start: number, stop: number, step?: number): number[]; + /** + * 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. + * @param stop Stop here. + * @return Array of numbers from 0 to `stop` with increments of 1. + * @note If start is not specified the implementation will never pull the step (step = arguments[2] || 0) + **/ + range(stop: number): number[]; + + /************ + * Functions * + *************/ + + /** + * 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 partial application. + * @param fn The function to bind `this` to `object`. + * @param object The `this` pointer whenever `fn` is called. + * @param arguments Additional arguments to pass to `fn` when called. + * @return `fn` with `this` bound to `object`. + **/ + bind(fn: Function, object: any, ...arguments: any[]): Function; + + + /** + * 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. + * @param object The object to bind the methods `methodName` to. + * @param methodNames The methods to bind to `object`, optional and if not provided all of `object`'s + * methods are bound. + **/ + bindAll(object: any, ...methodNames: string[]): void; + + /** + * Partially apply a function by filling in any number of its arguments, without changing its dynamic this value. + * A close cousin of bind. + * @param fn Function to partially fill in arguments. + * @param arguments The partial arguments. + * @return `fn` with partially filled in arguments. + **/ + partial(fn: Function, ...arguments: any[]): Function; + + /** + * 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. The default hashFunction just uses the first argument to the + * memoized function as the key. + * @param fn Computationally expensive function that will now memoized results. + * @param hashFn Hash function for storing the result of `fn`. + * @return Memoized version of `fn`. + **/ + memoize(fn: Function, hashFn?: (n: any) => string): Function; + + /** + * 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. + * @param fn Function to delay `waitMS` amount of ms. + * @param waitMS The amount of milliseconds to delay `fn`. + * @arguments Additional arguments to pass to `fn`. + **/ + delay(fn: Function, waitMS: number, ...arguments: any[]): void; + + /** + * 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. If you pass the optional arguments, they will be forwarded on + * to the function when it is invoked. + * @param fn The function to defer. + * @param arguments Additional arguments to pass to `fn`. + **/ + defer(fn: Function, ...arguments: any[]): void; + + /** + * Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, + * will only actually call the original function at most once per every wait milliseconds. Useful for + * rate-limiting events that occur faster than you can keep up with. + * @param fn Function to throttle `waitMS` ms. + * @param waitMS The number of milliseconds to wait before `fn` can be invoked again. + * @return `fn` with a throttle of `waitMS`. + **/ + throttle(fn: Function, waitMS: number): Function; + + /** + * Creates and returns a new debounced version of the passed function that will postpone its execution + * until after wait milliseconds have elapsed since the last time it was invoked. 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, and so on. + * + * Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead + * of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double + *-clicks on a "submit" button from firing a second time. + * @param fn Function to debounce `waitMS` ms. + * @param waitMS The number of milliseconds to wait before `fn` can be invoked again. + * @param immediate True if `fn` should be invoked on the leading edge of `waitMS` instead of the trailing edge. + * @return Debounced version of `fn` that waits `waitMS` ms when invoked. + **/ + debounce(fn: Function, waitMS: number, immediate?: bool): Function; + + /** + * Creates a version of the function that can only be called one time. Repeated calls to the modified + * function will have no effect, returning the value from the original call. Useful for initialization + * functions, instead of having to set a boolean flag and then check it later. + * @param fn Function to only execute once. + * @return Copy of `fn` that can only be invoked once. + **/ + once(fn: Function): Function; + + /** + * Creates a version of the function that will only be run after first being called count times. Useful + * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, + * before proceeding. + * @param count Number of times to be called before actually executing. + * @fn The function to defer execution `count` times. + * @return Copy of `fn` that will not execute until it is invoked `count` times. + **/ + after(count: number, fn: Function): Function; + + /** + * 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. + * @param fn Function to wrap. + * @param wrapper The function that will wrap `fn`. + * @return Wrapped version of `fn. + **/ + wrap(fn: Function, wrapper: (fn: Function, ...args: any[]) => any): Function; + + /** + * 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())). + * @param functions List of functions to compose. + * @return Composition of `functions`. + **/ + compose(...functions: Function[]): Function; + + /********** + * Objects * + ***********/ + + /** + * Retrieve all the names of the object's properties. + * @param object Retreive the key or property names from this object. + * @return List of all the property names on `object`. + **/ + keys(object: any): string[]; + + /** + * Return all of the values of the object's properties. + * @param object Retreive the values of all the properties on this object. + * @return List of all the values on `object`. + **/ + values(object: any): any[]; + + /** + * Convert an object into a list of [key, value] pairs. + * @param object Convert this object to a list of [key, value] pairs. + * @return List of [key, value] pairs on `object`. + **/ + pairs(object: any): any[][]; + + /** + * Returns a copy of the object where the keys have become the values and the values the keys. + * For this to work, all of your object's values should be unique and string serializable. + * @param object Object to invert key/value pairs. + * @return An inverted key/value paired version of `object`. + **/ + invert(object: any): any; + + /** + * 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. + * @param object Object to pluck all function property names from. + * @return List of all the function names on `object`. + **/ + functions(object: any): string[]; + + /** + * Copy all of the properties in the source objects over to the destination object, and return + * the destination object. It's in-order, so the last source will override properties of the + * same name in previous arguments. + * @param destination Object to extend all the properties from `sources`. + * @param sources Extends `destination` with all properties from these source objects. + * @return `destination` extended with all the properties from the `sources` objects. + **/ + extend(destination: any, ...sources: any[]): any; + + /** + * Return a copy of the object, filtered to only have values for the whitelisted keys + * (or array of valid keys). + * @param object Object to strip unwanted key/value pairs. + * @keys The key/value pairs to keep on `object`. + * @return Copy of `object` with only the `keys` properties. + **/ + pick(object: any, ...keys: string[]): any; + + /** + * Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). + * @param object Object to strip unwanted key/value pairs. + * @param keys The key/value pairs to remove on `object`. + * @return Copy of `object` without the `keys` properties. + **/ + omit(object: any, ...keys: string[]): any; + + /** + * Fill in null and undefined properties in object with values from the defaults objects, + * and return the object. As soon as the property is filled, further defaults will have no effect. + * @param object Fill this object with default values. + * @param defaults The default values to add to `object`. + * @return `object` with added `defaults` values. + **/ + defaults(object: any, ...defaults: any[]): any; + + /** + * Create a shallow-copied clone of the object. + * Any nested objects or arrays will be copied by reference, not duplicated. + * @param object Object to clone. + * @return Copy of `object`. + **/ + clone(object: any): any; + /** + * Create a shallow-copied clone of the object. + * Any nested objects or arrays will be copied by reference, not duplicated. + * @param list List to clone. + * @return Copy of `list`. + **/ + clone(list: any[]): any[]; + + /** + * 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. + * @param object Argument to `interceptor`. + * @param intercepter The function to modify `object` before continuing the method chain. + * @return Modified `object`. + **/ + tap(object: any, intercepter: Function): any; + + /** + * Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe + * reference to the hasOwnProperty function, in case it's been overridden accidentally. + * @param object Object to check for `key`. + * @param key The key to check for on `object`. + * @return True if `key` is a property on `object`, otherwise false. + **/ + has(object: any, key: string): bool; + + /** + * Performs an optimized deep comparison between the two objects, + * to determine if they should be considered equal. + * @param object Compare to `other`. + * @param other Compare to `object`. + * @return True if `object` is equal to `other`. + **/ + isEqual(object: any, other: any): bool; + + /** + * Returns true if object contains no values. + * @param object Check if this object has no properties or values. + * @return True if `object` is empty. + **/ + isEmpty(object: any): bool; + /** + * Returns true if the list contains no values. + * @param object Check if this list has no elements. + * @return True if `list` is empty. + **/ + isEmpty(list: any[]): bool; + + /** + * Returns true if object is a DOM element. + * @param object Check if this object is a DOM element. + * @return True if `object` is a DOM element, otherwise false. + **/ + isElement(object: any): bool; + + /** + * Returns true if object is an Array. + * @param object Check if this object is an Array. + * @return True if `object` is an Array, otherwise false. + **/ + isArray(object: any): bool; + + /** + * Returns true if value is an Object. Note that JavaScript arrays and functions are objects, + * while (normal) strings and numbers are not. + * @param object Check if this object is an Object. + * @return True of `object` is an Object, otherwise false. + **/ + isObject(object: any): bool; + + /** + * Returns true if object is an Arguments object. + * @param object Check if this object is an Arguments object. + * @return True if `object` is an Arguments object, otherwise false. + **/ + isArguments(object: any): bool; + + /** + * Returns true if object is a Function. + * @param object Check if this object is a Function. + * @return True if `object` is a Function, otherwise false. + **/ + isFunction(object: any): bool; + + /** + * Returns true if object is a String. + * @param object Check if this object is a String. + * @return True if `object` is a String, otherwise false. + **/ + isString(object: any): bool; + + /** + * Returns true if object is a Number (including NaN). + * @param object Check if this object is a Number. + * @return True if `object` is a Number, otherwise false. + **/ + isNumber(object: any): bool; + + /** + * Returns true if object is a finite Number. + * @param object Check if this object is a finite Number. + * @return True if `object` is a finite Number. + **/ + isFinite(object: any): bool; + + /** + * Returns true if object is either true or false. + * @param object Check if this object is a bool. + * @return True if `object` is a bool, otherwise false. + **/ + isBoolean(object: any): bool; + + /** + * Returns true if object is a Date. + * @param object Check if this object is a Date. + * @return True if `object` is a Date, otherwise false. + **/ + isDate(object: any): bool; + + /** + * Returns true if object is a RegExp. + * @param object Check if this object is a RegExp. + * @return True if `object` is a RegExp, otherwise false. + **/ + isRegExp(object: any): bool; + + /** + * 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. + * @param object Check if this object is NaN. + * @return True if `object` is NaN, otherwise false. + **/ + isNaN(object: any): bool; + + /** + * Returns true if the value of object is null. + * @param object Check if this object is null. + * @return True if `object` is null, otherwise false. + **/ + isNull(object: any): bool; + + /** + * Returns true if value is undefined. + * @param object Check if this object is undefined. + * @return True if `object` is undefined, otherwise false. + **/ + isUndefined(object: any): bool; + + /********** + * Utility * + ***********/ + + /** + * Give control of the "_" variable back to its previous owner. + * Returns a reference to the Underscore object. + * @return Underscore object reference. + **/ + noConflict(): Underscore; + + /** + * 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. + * @param value Identity of this object. + * @return `value`. + **/ + identity(value: any): any; + + /** + * Invokes the given iterator function n times. + * Each invocation of iterator is called with an index argument + * @param n Number of times to invoke `iterator`. + * @param iterator Function iterator to invoke `n` times. + * @param context `this` object in `iterator`, optional. + **/ + times(n: number, iterator: (n: number) => any , context?: any): any[]; + + /** + * Returns a random integer between min and max, inclusive. If you only pass one argument, + * it will return a number between 0 and that number. + * @param max The maximum random number. + * @return A random number between 0 and `max`. + **/ + random(max: number): number; + /** + * Returns a random integer between min and max, inclusive. If you only pass one argument, + * it will return a number between 0 and that number. + * @param min The minimum random number. + * @param max The maximum random number. + * @return A random number between `min` and `max`. + **/ + random(min: number, max: number): number; + + /** + * 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. + * @param object Mixin object containing key/function pairs to add to the Underscore object. + **/ + mixin(object: any): void; + + /** + * 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. Without prefix, returns an integer. + * @return Unique number ID. + **/ + uniqueId(): number; + /** + * 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. Without prefix, returns an integer. + * @param prefix A prefix string to start the unique ID with. + * @return Unique string ID beginning with `prefix`. + **/ + uniqueId(prefix: string): string; + + /** + * Escapes a string for insertion into HTML, replacing &, <, >, ", ', and / characters. + * @param str Raw string to escape. + * @return `str` HTML escaped. + **/ + escape(str: string): string; + + /** + * If the value of the named property is a function then invoke it; otherwise, return it. + * @param object Object to maybe invoke function `property` on. + * @param property The function by name to invoke on `object`. + * @return The result of invoking the function `property` on `object. + **/ + result(object: any, property: string): any; + + /** + * 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 + * <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %> When + * you evaluate a template function, pass in a data object that has properties corresponding to + * the template's free variables. If you're writing a one-off, you can pass the data object as + * the second parameter to template in order to render immediately instead of returning a template + * function. The settings argument should be a hash containing any _.templateSettings that should + * be overridden. + * @param templateString Underscore HTML template. + * @param data Data to use when compiling `templateString`. + * @param settings Settings to use while compiling. + * @return Returns the compiled Underscore HTML template. + **/ + template(templateString: string, data?: any, settings?: UnderscoreTemplateSettings): any; + + /** + * By default, Underscore uses ERB-style template delimiters, change the + * following template settings to use alternative delimiters. + **/ + templateSettings: UnderscoreTemplateSettings; + + /*********** + * Chaining * + ************/ + + /** + * Returns a wrapped object. Calling methods on this object will continue to return wrapped objects + * until value() is used. + * @param obj Object to chain. + * @return Wrapped `obj`. + **/ + chain(obj: any): UnderscoreOOPWrapper; + + /** + * Extracts the value of a wrapped object. + * @param obj Wrapped object to extract the value from. + * @return Value of `obj`. + **/ + value(obj: any): any; + + /************** + * OOP Wrapper * + **************/ + + /** + * Underscore OOP Wrapper, all Underscore functions that take an object + * as the first parameter can be invoked through this function. + * @param key First argument to Underscore object functions. + **/ + (obj: any): UnderscoreOOPWrapper; +} + +/** +* underscore.js template settings, set templateSettings or pass as an argument +* to 'template()' to overide defaults. +**/ +interface UnderscoreTemplateSettings { + /** + * Default value is '/<%([\s\S]+?)%>/g'. + **/ + evaluate?: RegExp; + + /** + * Default value is '/<%=([\s\S]+?)%>/g'. + **/ + interpolate?: RegExp; + + /** + * Default value is '/<%-([\s\S]+?)%>/g'. + **/ + escape?: RegExp; +} + +interface UnderscoreOOPWrapper { + + /************** + * Collections * + **************/ + + /** + * Wrapped type `any[]`. + * @see _.each + **/ + each( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * Wrapped type `object`. + * @see _.each + **/ + each( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * Alias for 'each'. + * @see each + **/ + forEach( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): void; + /** + * Alias for 'each'. + * @see each + **/ + forEach( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): void; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Wrapped type `object`. + * @see _.map + **/ + map( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * Alias for 'map'. + * @see map + **/ + collect( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Alias for 'map'. + * @see map + **/ + collect( + iterator: (value: any, key?: string, object?: Object) => any, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.reduce + **/ + reduce( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + inject( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduce'. + * @see reduce + **/ + foldl( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Wrapped type `any[]`. + * @see _.reduceRight + **/ + reduceRight( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Alias for 'reduceRight'. + * @see reduceRight + **/ + foldr( + iterator: (memo: any, element: any, index?: number, list?: any[]) => any, + memo: any, + context?: any): any; + + /** + * Wrapped type `any[]`. + * @see _.find + **/ + find( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + /** + * Alias for 'find'. + * @see find + **/ + detect( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any; + + + /** + * Wrapped type `any[]`. + * @see _.filter + **/ + filter( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Alias for 'filter'. + * @see filter + **/ + select( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.where + **/ + where(list: any[], properties: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.findWhere + **/ + findWhere(properties: any): any; + + /** + * Wrapped type `any[]`. + * @see _.reject + **/ + reject( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.all + **/ + all( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'all'. + * @see all + **/ + every( + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Wrapped type `any[]`. + * @see _.any + **/ + any( + list: any[], + iterator?: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Alias for 'any'. + * @see any + **/ + some( + list: any[], + iterator: (element: any, index?: number, list?: any[]) => bool, + context?: any): bool; + + /** + * Wrapped type `any[]`. + * @see _.contains + **/ + contains(value: any): bool; + + /** + * Alias for 'contains'. + * @see contains + **/ + include(value: any): bool; + + /** + * Wrapped type `any[]`. + * @see _.invoke + **/ + invoke(methodName: string, ...arguments: any[]): void; + + /** + * Wrapped type `any[]`. + * @see _.pluck + **/ + pluck(propertyName: string): any[]; + + /** + * Wrapped type `number[]`. + * @see _.max + **/ + max(): number; + /** + * Wrapped type `any[]`. + * @see _.max + **/ + max( + iterator: (element: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Wrapped type `number[]`. + * @see _.min + **/ + min(): number; + /** + * Wrapped type `any[]`. + * @see _.min + **/ + min( + iterator: (obj: any, index?: number, list?: any[]) => number, + context?: any): any; + + /** + * Wrapped type `any[]`. + * @see _.sortBy + **/ + sortBy( + iterator: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Wrapped type `any[]`. + * @see _.sortBy + **/ + sortBy( + iterator: string, + context?: any): any[]; + + /** + * Wrapped type `any[]`. + * @see _.groupBy + **/ + groupBy( + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: any[]; }; + /** + * Wrapped type `any[]`. + * @see _.groupBy + **/ + groupBy( + iterator: string, + context?: any): { [key: string]: any[]; }; + + /** + * Wrapped type `any[]`. + * @see _.countBy + **/ + countBy( + iterator: (element: any, index?: number, list?: any[]) => string, + context?: any): { [key: string]: number; }; + /** + * Wrapped type `any[]`. + * @see _.countBy + **/ + countBy( + iterator: string, + context?: any): { [key: string]: number; }; + + /** + * Wrapped type `any[]`. + * @see _.shuffle + **/ + shuffle(): any[]; + + /** + * Wrapped type `any`. + * @see _.toArray + **/ + toArray(): any[]; + + /** + * Wrapped type `any`. + * @see _.size + **/ + size(): number; + + /********* + * Arrays * + **********/ + + /** + * Wrapped type `any[]`. + * @see _.first + **/ + first(): any; + /** + * Wrapped type `any[]`. + * @see _.first + **/ + first(n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + head(): any; + /** + * Alias for 'first'. + * @see first + **/ + head(n: number): any[]; + + /** + * Alias for 'first'. + * @see first + **/ + take(): any; + /** + * Alias for 'first'. + * @see first + **/ + take(n: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.initial + **/ + initial(n?: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.last + **/ + last(): any; + /** + * Wrapped type `any[]`. + * @see _.last + **/ + last(n: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.rest + **/ + rest(index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + tail(index?: number): any[]; + + /** + * Alias for 'rest'. + * @see rest + **/ + drop(index?: number): any[]; + + /** + * Wrapped type `any[]`. + * @see _.compact + **/ + compact(): any[]; + + /** + * Wrapped type `any`. + * @see _.flatten + **/ + flatten(shallow?: bool): any; + + /** + * Wrapped type `any[]`. + * @see _.without + **/ + without(...values: any[]): any[]; + + /** + * Wrapped type `any[][]`. + * @see _.union + **/ + union(...arrays: any[][]): any[]; + + /** + * Wrapped type `any[][]`. + * @see _.intersection + **/ + intersection(...arrays: any[][]): any[]; + + /** + * Wrapped type `any[]`. + * @see _.difference + **/ + difference(...others: any[]): any[]; + + /** + * Wrapped type `any[]`. + * @see _.uniq + **/ + uniq( + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + /** + * Wrapped type `any[]`. + * @see _.uniq + **/ + uniq( + iterator?: (element: any, index?: number, list?: any[]) => any, + context?: any): any[]; + + /** + * Alias for 'uniq'. + * @see uniq + **/ + unique( + isSorted?: bool, + iterator?: (element: any, index?: number, list?: any[]) => any): any[]; + + /** + * Wrapped type `any[][]`. + * @see _.zip + **/ + zip(...arrays: any[][]): any[][]; + + /** + * Wrapped type `any[][]`. + * @see _.object + **/ + object(...keyValuePairs: any[][]): any; + + /** + * Wrapped type `any[]`. + * @see _.indexOf + **/ + indexOf(value: any, isSorted?: bool): number; + + /** + * Wrapped type `any[]`. + * @see _.lastIndexOf + **/ + lastIndexOf(value: any, from?: number): number; + + /** + * Wrapped type `any[]`. + * @see _.sortedIndex + **/ + sortedIndex(value: any, iterator?: (element: any) => number): number; + + /** + * Wrapped type `number`. + * @see _.range + **/ + range(stop: number, step?: number): number[]; + /** + * Wrapped type `number`. + * @see _.range + **/ + range(): number[]; + + /************ + * Functions * + *************/ + + /** + * Wrapped type `Function`. + * @see _.bind + **/ + bind(object: any, ...arguments: any[]): Function; + + + /** + * Wrapped type `object`. + * @see _.bindAll + **/ + bindAll(...methodNames: string[]): void; + + /** + * Wrapped type `Function`. + * @see _.partial + **/ + partial(...arguments: any[]): Function; + + /** + * Wrapped type `Function`. + * @see _.memoize + **/ + memoize(hashFn?: (n: any) => string): Function; + + /** + * Wrapped type `Function`. + * @see _.delay + **/ + delay(waitMS: number, ...arguments: any[]): void; + + /** + * Wrapped type `Function`. + * @see _.defer + **/ + defer(...arguments: any[]): void; + + /** + * Wrapped type `Function`. + * @see _.throttle + **/ + throttle(waitMS: number): Function; + + /** + * Wrapped type `Function`. + * @see _.debounce + **/ + debounce(waitMS: number, immediate?: bool): Function; + + /** + * Wrapped type `Function`. + * @see _.once + **/ + once(): Function; + + /** + * Wrapped type `number`. + * @see _.after + **/ + after(fn: Function): Function; + + /** + * Wrapped type `Function`. + * @see _.wrap + **/ + wrap(wrapper: (fn: Function, ...args: any[]) => any): Function; + + /** + * Wrapped type `Function[]`. + * @see _.compose + **/ + compose(...functions: Function[]): Function; + + /********** + * Objects * + ***********/ + + /** + * Wrapped type `object`. + * @see _.keys + **/ + keys(): string[]; + + /** + * Wrapped type `object`. + * @see _.values + **/ + values(): any[]; + + /** + * Wrapped type `object`. + * @see _.pairs + **/ + pairs(): any[][]; + + /** + * Wrapped type `object`. + * @see _.invert + **/ + invert(): any; + + /** + * Wrapped type `object`. + * @see _.functions + **/ + functions(): string[]; + + /** + * Wrapped type `object`. + * @see _.extend + **/ + extend(...sources: any[]): any; + + /** + * Wrapped type `object`. + * @see _.pick + **/ + pick(...keys: string[]): any; + + /** + * Wrapped type `object`. + * @see _.omit + **/ + omit(...keys: string[]): any; + + /** + * Wrapped type `object`. + * @see _.defaults + **/ + defaults(...defaults: any[]): any; + + /** + * Wrapped type `object`. + * @see _.clone + **/ + clone(object: any): any; + /** + * Wrapped type `any[]`. + * @see _.clone + **/ + clone(list: any[]): any[]; + + /** + * Wrapped type `object`. + * @see _.tap + **/ + tap(intercepter: Function): any; + + /** + * Wrapped type `object`. + * @see _.has + **/ + has(key: string): bool; + + /** + * Wrapped type `object`. + * @see _.isEqual + **/ + isEqual(other: any): bool; + + /** + * Wrapped type `object`. + * @see _.isEmpty + **/ + isEmpty(object: any): bool; + /** + * Wrapped type `any[]`. + * @see _.isEmpty + **/ + isEmpty(list: any[]): bool; + + /** + * Wrapped type `object`. + * @see _.isElement + **/ + isElement(): bool; + + /** + * Wrapped type `object`. + * @see _.isArray + **/ + isArray(): bool; + + /** + * Wrapped type `object`. + * @see _.isObject + **/ + isObject(): bool; + + /** + * Wrapped type `object`. + * @see _.isArguments + **/ + isArguments(): bool; + + /** + * Wrapped type `object`. + * @see _.isFunction + **/ + isFunction(): bool; + + /** + * Wrapped type `object`. + * @see _.isString + **/ + isString(): bool; + + /** + * Wrapped type `object`. + * @see _.isNumber + **/ + isNumber(): bool; + + /** + * Wrapped type `object`. + * @see _.isFinite + **/ + isFinite(): bool; + + /** + * Wrapped type `object`. + * @see _.isBoolean + **/ + isBoolean(): bool; + + /** + * Wrapped type `object`. + * @see _.isDate + **/ + isDate(): bool; + + /** + * Wrapped type `object`. + * @see _.isRegExp + **/ + isRegExp(): bool; + + /** + * Wrapped type `object`. + * @see _.isNaN + **/ + isNaN(): bool; + + /** + * Wrapped type `object`. + * @see _.isNull + **/ + isNull(): bool; + + /** + * Wrapped type `object`. + * @see _.isUndefined + **/ + isUndefined(): bool; + + /********** + * Utility * + ***********/ + + /** + * Wrapped type `any`. + * @see _.identity + **/ + identity(): any; + + /** + * Wrapped type `number`. + * @see _.times + **/ + times(iterator: (n: number) => any, context?: any): any[]; + + /** + * Wrapped type `number`. + * @see _.random + **/ + random(): number; + /** + * Wrapped type `number`. + * @see _.random + **/ + random(max: number): number; + + /** + * Wrapped type `object`. + * @see _.mixin + **/ + mixin(): void; + + /** + * Wrapped type `string`. + * @see _.uniqueId + **/ + uniqueId(): string; + + /** + * Wrapped type `string`. + * @see _.escape + **/ + escape(): string; + + /** + * Wrapped type `object`. + * @see _.result + **/ + result(property: string): any; + + /** + * Wrapped type `string`. + * @see _.template + **/ + template(data?: any, settings?: UnderscoreTemplateSettings): any; + + /*********** + * Chaining * + ************/ + + /** + * Wrapped type `any`. + * @see _.chain + **/ + chain(): any; + + /** + * Wrapped type `any`. + * @see _.value + **/ + value(): any; +} + +declare var _: Underscore;