racl101/Simple Math Captcha-like verification JavaScript script that uses jQuery (form) validation plugin ( JavaScript)
jQuery(document).ready(function() {
var send_email_form = jQuery("form#my-form");
var lowerBound = 1;
var upperBound = 10;
// to generate random numbers between a range that starts somewhere other than
// zero use this formula where m is the lowest possible integer value of the range
// and n equals the top number of the range.
// Math.floor(Math.random() * (n - m + 1)) + m
// generate random numbers between lowerBound and upperBound (inclusive)
var a = Math.floor(Math.random() * (upperBound - lowerBound + 1)) + lowerBound;
var b = Math.floor(Math.random() * (upperBound - lowerBound + 1)) + lowerBound;
jQuery("label#arithmetic_expression").html(a + " + " + b + " = ");
jQuery("input#eqtn_soln").val(a+b);
var validation_rules = {
name: "required",
email: {
required: true,
email: true
},
subject: "required",
message: "required",
sum: {
required: true,
equalTo: "input#eqtn_soln"
}
};
var validation_messages = {
name: "please enter your name",
email: {
required: "Please enter your email address",
email: "Please enter a valid email address"
},
subject: "please enter a message subject",
message: "please enter the message",
sum: {
required: "please answer the equation",
equalTo: "please answer the equation correctly"
}
};
//form validation with Javascript
send_email_form.validate({
rules: validation_rules,
messages: validation_messages,
//errorClass: "form-error-style",
errorPlacement: function(error, element){
// places the error message after the element one line break below
error.insertAfter(jQuery("<br />").insertAfter(element));
}
});
});
Don't forget to include jQuery validation plugin before this snippet. You can find it here:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
mlange/Math functions ( JavaScript)
Math.abs(n) // Returns the absolute value of n Math.acos(n) // Returns (in radians) cos-1 of n Math.asin(n) // Returns (in radians) sin-1 of n Math.atan(n) // Returns (in radians) tan-1 of n Math.atan2(n,k) // Returns the angle (rads) from cartesian coordinates 0,0 to n,k Math.ceil(n) // Returns n rounded up to the nearest whole number Math.cos(n) // Returns cos n (where n is in radians) Math.exp(n) // Returns en Math.floor(n) // Returns n rounded down to the nearest whole number Math.log(n) // Returns ln(n) // Note, to find log10(n), use Math.log(n) / Math.log(10) Math.max(a,b,c,...) // Returns the largest number Math.min(a,b,c,...) Returns the smallest number Math.pow(n,k) // Returns n^k Math.random() // Returns a random number between 0 and 1 Math.round(n) // Returns n rounded up or down to the nearest whole number Math.sin(n) // Returns sin n (where n is in radians) Math.sqrt(n) // Returns the square root of n Math.tan(n) // Returns tan n (where n is in radians)
crevier/date math ( JavaScript)
function addToDate(date,days) {
var yyyy,mm,dd,idate,newdate;
date = String(date);
yyyy = date.substr(0,4);
mm = date.substr(4,2) - 1;
dd = date.substr(6,2) - 0;
idate = new Date(yyyy,mm,dd,0,0,0,0);
idate.setTime(idate.getTime()+60000*60*24*days);
yyyy = idate.getYear(); if (yyyy < 1000) yyyy += 1900;
mm = idate.getMonth() + 1; if (mm < 10) mm = '0' + mm;
dd = idate.getDate(); if (dd < 10) dd = '0' + dd;
newdate = parseInt(String(yyyy) + String(mm) + String(dd));
return newdate;
}
This function accepts a date string (yyyymmdd), along with a number of days (integer) and adds the days to the date. It then returns the new date string (yyyymmdd).
stephanepericat/Captcha with Mootools ( JavaScript)
/**
* author : Stephane P. Pericat
* date : 2010-03-01
*/
PHP Code:
<?php
require "recaptcha/recaptchalib.php";
if($_POST) {
$resp = recaptcha_check_answer(
"6LdrkwsAAAAAAHX2b45bn_...", //put your recaptcha private key here
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]
);
if ($resp->is_valid) {
echo json_encode(true);
} else {
echo json_encode(false);
}
}
?>
//-----------------------------------------------
Javascript front-end:
new Asset.javascript('http://api.recaptcha.net/js/recaptcha_ajax.js');
$(document.body).addEvent('submit', function(event) {
event.stop();
var challenge = Recaptcha.get_challenge();
var response = Recaptcha.get_response();
var control = new Request.JSON({
url: 'control.php',
data : {
recaptcha_challenge_field : challenge,
recaptcha_response_field : response
},
method: 'post',
onComplete : function (result) {
if(result == true) {
Recaptcha.destroy();
console.log(result);
} else {
Recaptcha.reload();
}
}
}).send();
});
A simple JSON request to validate a captcha control (using the php plugin provided by Recaptcha)
zackfern/Addition CAPTCHA ( jQuery)
function random_between(to, from) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
$(document).ready(function() {
var num1 = random_between(0,5)
var num2 = random_between(5,10);
$('label[for="captcha"]').text("What is "+num1+" + "+num2);
$('form').submit(function() {
if($('#captcha').val() == (num1+num2)) {
$('form').submit();
}
else {
alert("Your CAPTCHA IS NOT valid!");
return false;
}
});
});
rolandog/Math.js ( JavaScript)
/**
* Math.js
* http://rolandog.com/math-js/
*
* License: Creative Commons Attribution-Share Alike 3.0 Unported.
* http://creativecommons.org/licenses/by-sa/3.0/
*
* @projectDescription A library with Mathematical functions.
* @author Rolando Garza rolandog@gmail.com
*/
"use strict";
/**
* An extension to the Array object that filters out repeated values.
* @return(Array) Returns the filtered array.
*/
if (Array.unique !== undefined) {
Array.prototype.unique = function Array_unique() {
var a = [], l = this.length, i = 0, j;
while (i < l) {
for (j = i + 1; j < l; j += 1) {
if (this[i] === this[j]) {
i += 1;
j = i;
}
}
a.push(this[i]);
i += 1;
}
return a;
};
}
/**
* An extension to the Array object that counts the instances of 'a'.
* @return(Number) Counts how many 'a' there are in the Array.
*/
if (Array.count !== undefined) {
Array.prototype.count = function Array_count(a) {
var r = 0, i;
for (i = 0; i < this.length; i += 1) {
r += this[i] === a ? 1 : 0;
}
return r;
};
}
/**
* @classDescription Contains some helpful functions.
*/
Math.js = {
/**
* Duplicates argument objects or arrays, and returns them as arrays.
* @param(Object) as An Object or an Array.
* @return(Array) A duplicated array.
*/
copy: function Math_js_copy(as) {
var a = 0, r = [];
try {
while (a < as.length) {
r.push(as[a]);
a += 1;
}
} catch (e) {
for (a in as) {
if (as.hasOwnProperty(a) && as[a]) {
r.push(a);
}
}
}
return r;
},
/**
* Sorts an array of numbers in ascending order properly.
* @param(Number) a A Number.
* @param(Number) b A Number.
* @return(Number) The comparison between those numbers.
*/
ascending: function Math_js_ascending(a, b) {
return a - b;
},
/**
* Sorts an array of numbers in descending order properly.
* @param(Number) a A Number.
* @param(Number) b A Number.
* @return(Number) The comparison between those numbers.
*/
descending: function Math_js_descending(a, b) {
return b - a;
}
};
/**
* An extension to the Math object that accepts Arrays or Numbers
* as an argument and returns the sum of all numbers.
* @param(Array) a A Number or an Array of numbers.
* @return(Number) Returns the sum of all numbers.
*/
Math.sum = function Math_sum(a) {
var r = 0;
a = a.length ? a:Math.js.copy(arguments);
while (a.length) {
r += a.shift();
}
return r;
};
/**
* An extension to the Math object that accepts Arrays or Numbers
* as an argument and returns the product of all numbers.
* @param(Array) a A Number or an Array of numbers.
* @return(Number) Returns the product of all numbers.
*/
Math.product = function Math_product(a) {
var r = 1;
a = a.length ? a:Math.js.copy(arguments);
while (a.length) {
r *= a.shift();
}
return r;
};
/**
* An extension to the Math object that accepts a Number
* and returns the factorial.
* @param(Array) a A Number or an Array of numbers.
* @return(Number) Returns the product of all numbers.
*/
Math.factorial = function Math_factorial(a) {
return (a <= 1) ? 1 : a * Math.factorial(a - 1);
};
/**
* Returns the Greatest Common Divisor using Euclid's algorithm.
* @param(Array) a An Array of integers.
* @return(Number) Returns the Greatest Common Divisor.
*/
Math.gcd = function Math_gcd(a) {
a = a.length ? a:Math.js.copy(arguments);
var l = a.length;
if (l < 2) {
throw "Error: Must have at least two integers.";
}
while (l - 2) {
a.push(Math.gcd(a.shift(), a.shift()));
l = a.length;
}
return a[1] === 0 ? a[0] : Math.gcd(a[1], a[0] % a[1]);
};
/**
* Returns the Least Common Multiple.
* @param(Array) a An integer or an Array of integers.
* @return(Number) Returns the Least Common Multiple.
*/
Math.lcm = function Math_lcm(a) {
a = a.length ? a:Math.js.copy(arguments);
var l = a.length;
while (l - 2) {
a.unshift(Math.lcm(a.shift(), a.shift()));
l = a.length;
}
return a[0] * a[1] / Math.gcd(a[0], a[1]);
};
/**
* Determines if a number is prime.
* @param(Number) a An integer.
* @return(Boolean) true if a number is prime.
*/
Math.isPrime = function Math_isPrime(n) {
if (n !== Math.floor(n) || n <= 1 || (n % 2 === 0 && n !== 2)) {
return false;
}
if (n > 4) {
var i, r = Math.ceil(Math.sqrt(n));
for (i = 3; i <= r; i += 2) {
if (n % i === 0) {
return false;
}
}
}
return true;
};
/**
* Returns the factors of a number in an array.
* @param(Number) a An integer.
* @return(Array) Returns the factors of 'a' in an array.
*/
Math.factors = function Math_factors(a) {
var n = Math.abs(a), r = Math.floor(Math.sqrt(n)), i = 2, f = [];
while (i <= n && i <= r) {
if (n % i === 0) {
f.push(i);
n /= i;
}
else {
i += 1;
}
}
if (a !== Math.abs(a)) {
f.unshift(-1);
}
return f;
};
/**
* Returns the divisors of a number in an array.
* @param(Number) a An integer.
* @param(Boolean) b If true, returns the 'proper' divisors.
* @return(Array) Returns the divisors of 'a' in an array.
*/
Math.divisors = function Math_divisors(a, b) {
var n = Math.abs(a), r = Math.sqrt(n), i = 1, d = [];
while (i <= r) {
if (a % i === 0) {
d.push(i);
if (i !== r) {
d.push(a / i);
}
}
i += 1;
}
d = d.sort(Math.js.ascending);
if (b) {
d.pop();
}
return d;
};
/**
* Returns a Fibonacci sequence in an array.
* @param(Number) l The upper limit.
* @param(Number) a The starting value.
* @param(Number) b The next value in the sequence.
* @return(Array) Returns the sequence of Fibonacci numbers.
*/
Math.fibonacci = function Math_fibonacci(l, a, b) {
a = a === undefined ? 1:a;
b = b === undefined ? 2:b;
var r = [a, b];
while (r[r.length - 1] < l) {
r.push(r[r.length - 1] + r[r.length - 2]);
}
return r;
};
/**
* @classDescription Some big Integer functions
*/
Math.bigInt = {};
/**
* Returns big Integer factorial numbers
*/
Math.bigInt.factorial = function Math_bigInt_factorial(a) {
var b = a.toString(), i, j, k, l, o, t, c;
b = b.split("").reverse();
for (i = 0; i < b.length; i += 1) {
b[i] = parseInt(b[i], 10);
}
for (i = a - 1; i >= 2; i -= 1) {
l = b.length;
for (j = 0; j < l; j += 1) {
b[j] *= i;
}
for (j = 0; j < l; j += 1) {
t = b[j].toString().split("").reverse().join("");
o = t.length;
for (k = 0; k < o; k += 1) {
c = parseInt(t.charAt(k), 10);
b[j + k] = b[j + k] ? (k ? b[j + k] : 0) + c:c;
}
}
}
return b.reverse().join("");
};
/**
* Returns the sum of big Integers
*/
Math.bigInt.sum = function Math_bigInt_sum(a) {
function flip(z) {
z = typeof(z) === "string" ? z : "" + z;
z = z.split("").reverse();
for (var i = 0; i < z.length; i += 1) {
z[i] = parseInt(z[i], 10);
}
return z;
}
function sum(A, B) {
var C = [], i, l = Math.max(A.length, B.length);
for (i = 0; i < l; i += 1) {
C[i] = (A[i]?A[i]:0) + (B[i]?B[i]:0) + (C[i]?C[i]:0);
if (C[i] >= 10) {
C[i] -= 10;
C[i + 1] = C[i + 1] ? C[i + 1] + 1 : 1;
}
}
return C;
}
a = a.length && typeof(a) !== "string" ? a:Math.js.copy(arguments);
var b = a.shift();
b = flip(b);
while (a.length) {
b = sum(b, flip(a.shift()));
}
return b.reverse().join("");
};
Math.bigInt.multiply = function Math_bigInt_multiply(a) {
function toInt(z) {
for (var i = 0; i < z.length; i += 1) {
z[i] = parseInt(z[i], 10);
}
return z;
}
function check(x) {
var i, t, z = Math.js.copy(x).reverse();
for (i = 0; i < z.length; i += 1) {
if (z[i] >= 10) {
t = parseInt(z[i] / 10, 10);
z[i] = z[i] % 10;
z[i + 1] = z[i + 1] !== undefined ? z[i + 1] + t : t;
}
}
z.reverse();
while (z[0] === 0) {
z.shift();
}
return z.length !== 0 ? z : [0];
}
function fillz(z) {
var r = [];
while (z > 0) {
r.push(0);
z -= 1;
}
return r;
}
function product(f, g) {
var i, j, k, r = [], t, u, z;
for (j = g.length - 1; j >= 0; j -= 1) {
t = [];
//multiplies everything
for (i = f.length - 1; i >= 0; i -= 1) {
t[i] = f[i] * g[j];
}
//fills an array with zeros, according to the magnitude order of the number
z = fillz(g.length - j - 1);
//checks that every number in the array is below 10.
u = check(t);
//joins the number array and the zeros, and converts to string..
t = u.concat(z);
t = t.join("");
r.unshift(t);
}
return toInt(Math.bigInt.sum(r).split(""));
}
a = a.length && typeof(a) !== "string" ? a:Math.js.copy(arguments);
var b = a.shift(), c;
b = toInt(("" + b).split(""));
while (a.length) {
c = toInt(("" + a.shift()).split(""));
b = product(b, c);
}
return b.length ? b.join("") : "0";
};
//The limit of integer precision: parseInt("9007199254740994", 10)
An ECMAScript library that adds some basic Mathematical functions to the Math object.
hellowouter/Using Math.min and Math.max for an array ( JavaScript)
/* min/max number in an array */ var numbers = [5, 6, 2, 3, 7]; /* using Math.min/Math.max apply */ var max = Math.max.apply(null, numbers); /* This about equal to Math.max(numbers[0], ...) or Math.max(5, 6, ..) */ var min = Math.min.apply(null, numbers);
Clever usage of apply allows you to use built-ins functions for some tasks that otherwise probably would have been written by looping over the array values. As an example here we are going to use Math.max/Math.min to find out the maximum/minimum value in an array.
Ilker x/Strong Captcha for asp.net ( C#)
using System;
using System.Collections;
using System.Data;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
// Kodu Yazan : Ilker Sly
/// <summary>
/// Summary description for Captcha
/// </summary>
public class Captcha
{
public Captcha()
{
//
// TODO: Add constructor logic here
//
}
public string Text
{
get { return this.text; }
}
public Bitmap Image
{
get { return this.image; }
}
public int Width
{
get { return this.width; }
}
public int Height
{
get { return this.height; }
}
private string text;
private int width;
private int height;
private string familyName;
private Bitmap image;
// // // // SETTINGS
private readonly string[] fontList = new string[] { "Times New Roman", "Verdana", "Comic Sans MS", "Arial", "Courier New", "Georgia", "Impact", "Palatino Linotype", "Lucida Console", "Marlett" };
private static int charLength = 5;
// // // // END SETTINGS
private Random random = new Random();
public Captcha(string s, int width, int height)
{
this.text = s;
HttpContext.Current.Session["CaptchaCode"] = s;
this.SetDimensions(width, height);
this.SetFamilyName(fontList[random.Next(0,fontList.Length-1)]);
this.GenerateImage();
}
~Captcha()
{
Dispose(false);
}
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.image.Dispose();
}
}
private void SetDimensions(int width, int height)
{
if (width <= 0)
throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
this.width = width;
this.height = height;
}
private void SetFamilyName(string familyName)
{
try
{
Font font = new Font(this.familyName, 12F);
this.familyName = familyName;
font.Dispose();
}
catch
{
this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
}
}
// Kodu Yazan : Ilker Sly
private void GenerateImage()
{
Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);
Color backColor = Color.FromArgb(random.Next(128, 255), random.Next(128, 255), random.Next(128, 255));
Color foreColor = ColorInvert(backColor);
HatchBrush hatchBrush = new HatchBrush(RandomEnum<HatchStyle>(), backColor, Color.White);
g.FillRectangle(hatchBrush, rect);
SizeF size;
float fontSize = rect.Height + 11;
Font font;
do
{
fontSize--;
font = new Font(this.familyName, fontSize, FontStyle.Bold);
size = g.MeasureString(this.text, font);
} while (size.Width > rect.Width);
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
GraphicsPath path = new GraphicsPath();
path.AddString(this.text, font.FontFamily, (int) font.Style, font.Size, rect, format);
float v = 4F;
PointF[] points =
{
new PointF(this.random.Next(rect.Width)/v, this.random.Next(rect.Height)/v),
new PointF(rect.Width - this.random.Next(rect.Width)/v, this.random.Next(rect.Height)/v),
new PointF(this.random.Next(rect.Width)/v, rect.Height - this.random.Next(rect.Height)/v),
new PointF(rect.Width - this.random.Next(rect.Width)/v, rect.Height - this.random.Next(rect.Height)/v)
};
Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
hatchBrush = new HatchBrush(RandomEnum<HatchStyle>(), Color.DimGray, foreColor);
g.FillPath(hatchBrush, path);
int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i < (int) (rect.Width*rect.Height/30F); i++)
{
int x = this.random.Next(rect.Width);
int y = this.random.Next(rect.Height);
int w = this.random.Next(m/50);
int h = this.random.Next(m/50);
g.FillEllipse(hatchBrush, x, y, w, h);
}
font.Dispose();
hatchBrush.Dispose();
g.Dispose();
this.image = bitmap;
}
public static string generateRandomCode()
{
ArrayList Kod = new ArrayList();
Random rnd = new Random();
for (char i = 'A'; i <= 'Z'; i++)
Kod.Add(i);
for (char i = 'a'; i <= 'z'; i++)
Kod.Add(i);
for (char i = '0'; i <= '9'; i++)
Kod.Add(i);
string val = "";
for (int i = 0; i < charLength; i++)
val += Kod[rnd.Next(Kod.Count)].ToString();
return val;
}
private Random rand = new Random();
private T RandomEnum<T>()
{
T[] values = (T[])Enum.GetValues(typeof(T));
return values[rand.Next(0, values.Length)];
}
private Color ColorInvert(Color colorIn)
{
return Color.FromArgb(colorIn.A, Color.White.R - colorIn.R,
Color.White.G - colorIn.G, Color.White.B - colorIn.B);
}
}
Strong Captcha for asp.net Random color, Random font
sergiomas/Comprobar si un valor es un número entero ( JavaScript)
esEntero: function(valor){
if(!isNaN(valor)){
for(var i = 0; i<valor.length;i++){
if(valor.charCodeAt(i)<48 || valor.charCodeAt(i)>57)
return false;
}
}else{
return false;
}
return true;
}
lynseydesign/jQuery UI slider with mathematical estimates ( jQuery)
<script type="text/javascript">
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
$(function(){
// Slider
$('#slider').slider({
value: 1,
min: 1,
max: 99,
step: 2,
orientation: 'vertical',
slide: function( event, ui ) {
$("#mill" ).val( "$ " + ui.value + " M" );
$("#week" ).val( "$ " + addCommas(Math.round(ui.value/.000052)));
$("#day" ).val( "$ " + addCommas(Math.round((ui.value/.000052)/5)));
$("#hour" ).val( "$ " + addCommas(Math.round(((ui.value/.000052)/5)/8)));
}
});
var mill= $("#slider").slider( "value");
$("#mill" ).val( "$ " + mill + " M" );
$("#week" ).val( "$ " + addCommas(Math.round(mill/.000052)));
$("#day" ).val( "$ " + addCommas(Math.round((mill/.000052)/5)));
$("#hour" ).val( "$ " + addCommas(Math.round(((mill/.000052)/5)/8)));
});
</script>
mikael12/Form processing with input checking, simple captcha and error reporting ( PHP)
<?php
$js_back = 'javascript:history.go(-1)';
if (isset($_POST['send']))
{
if ($_POST['captcha'] != 'hello')
die('<p class="error">Antispam failed. <a href="'.$js_back.'">Try again</p>');
$secured = array();
$secured = array_map('htmlspecialchars', array_map('strip_tags', $_POST));
extract($secured);
$inputs = array('cname' => 'Firstname, surname', 'cemail' => 'Email', 'msg' => 'Message');
foreach ($inputs as $key => $value)
{
if (empty(${$key}))
die('<p class="error">Input '.$value.' is required. <a href="'.$js_back.'">Try again</a></p>');
}
// Code...
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<table>
<tbody>
<tr>
<td><label for="cname">Firstname, surname:</label></td>
<td><input type="text" name="cname" id="cname" size="40" /></td>
</tr>
<tr>
<td><label for="cemail">E-mail:</label></td>
<td><input type="text" name="cemail" id="cemail" size="40" /></td>
</tr>
<tr>
<td><label for="msg">Message:</label></td>
<td><textarea name="msg" rows="8" cols="38" id="msg"></textarea></td>
</tr>
<tr>
<td>Antispam:</td>
<td><input type="text" name="captcha" /> write in "hello"</td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="send" value="Send" /></td>
</tr>
</tbody>
</table>
</form>
devnull69/Array shuffle without bias ( JavaScript)
// (C) Stephen "felgall" http://www.codingforums.com/showthread.php?t=252059
Array.prototype.shuffle = function() {
var s = [];
while (this.length) s.push(this.splice(Math.random() * this.length, 1));
while (s.length) this.push(s.pop());
return this;
}
The usual way to shuffle an array uses the .sort() method with Math.round(Math.random())-0.5 This solution is highly biased based on the sort algorithm used by the browsers. A sort comparison operation has to fulfill the condition "if a>b then b<a" for two consecutive calculations which won't work with this. So here is a possible unbiased solution for a .shuffle() method
StevenW721/Return Age from Date of Birth ( JavaScript)
/**
* Calculate Age
*
* Calculates the amount of time since the date specified with yr, mon, and day.
* The parameter "countunit" can be "years", "months", or "days" and is the duration
* between the specified day and today in the selected denomination. The "decimals"
* parameter allows you to set a decimal place to round to for days and months return
* values. Rounding is also meant for days and months and can be "roundup" or "rounddown"
* based solely on the properties of Math.ceil and math.floor respectively.
* Sample - displayage(1997, 11, 24, "years", 0, "rounddown")
*/
function displayage( yr, mon, day, countunit, decimals, rounding ) {
// Starter Variables
today = new Date();
yr = parseInt(yr);
mon = parseInt(mon);
day = parseInt(day);
var one_day = 1000*60*60*24;
var one_month = 1000*60*60*24*30;
var one_year = 1000*60*60*24*30*12;
var pastdate = new Date(yr, mon-1, day);
var return_value = 0;
finalunit = ( countunit == "days" ) ? one_day : ( countunit == "months" ) ? one_month : one_year;
decimals = ( decimals <= 0 ) ? 1 : decimals * 10;
if ( countunit != "years" ) {
if ( rounding == "rounddown" )
return_value = Math.floor ( ( today.getTime() - pastdate.getTime() ) / ( finalunit ) * decimals ) / decimals;
else
return_value = Math.ceil ( ( today.getTime() - pastdate.getTime() ) / ( finalunit ) * decimals ) / decimals;
} else {
yearspast = today.getFullYear()-yr-1;
tail = ( today.getMonth() > mon - 1 || today.getMonth() == mon - 1 && today.getDate() >= day ) ? 1 : 0;
return_value = yearspast + tail;
}
return return_value;
}
Calculates the amount of time since the date specified with yr, mon, and day. The parameter "countunit" can be "years", "months", or "days" and is the duration between the specified day and today in the selected denomination. The "decimals" parameter allows you to set a decimal place to round to for days and months return values. Rounding is also meant for days and months and can be "roundup" or "rounddown" based solely on the properties of Math.ceil and math.floor respectively. Sample - displayage(1997, 11, 24, "years", 0, "rounddown")
hand4ever/currying in javascript ( JavaScript)
Array.prototype.each = function(fn){
return this.length? [fn(this[0])].concat(this.slice(1).each(fn)): [];
};
//e.g.
var arr = [1,2,3,4].each(function(x){return x*2;});
//alert(arr);//[2,3,6,8]
each in Array,It can operate each element in Array. e.g. var result = [1,2,3,4].each(function(x){return Math.sqrt(x);}); //it return sqrt in [1,2,3,4]'s each item
badiali/Numero aleatorio por rango ( JavaScript)
function aleatorio(inferior,superior){
numPosibilidades = superior - inferior
aleat = Math.random() * numPosibilidades
aleat = Math.round(aleat)
return parseInt(inferior) + aleat
}