Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

implement mootools/mootools-core#2268 (String.prototype.ms)

  • Loading branch information...
commit 81ff7d8bde740a682aa743501898e632e47f398d 1 parent 0795e1c
@alpha123 alpha123 authored
View
26 Docs/Types/String.Extras.md
@@ -181,8 +181,34 @@ Truncates a string after the given number of characters.
'This is some random text'.truncate(15, '--'); // This is some ra--
'This is some random text'.truncate(15, '…', ' '); // This is some…
+String Method: ms {#String:ms}
+------------------------------------------
+
+Converts a string with units, such as '5m', to milliseconds, for use with e.g. [Function.delay][].
+
+### Syntax
+
+ '3s'.ms()
+
+### Returns
+
+* (*number*) the string converted to milliseconds
+
+### Examples
+
+ theFunction.delay('10s'.ms()); // Executes theFunction in 10,000 milliseconds
+
+### Notes
+
+ Currently supported units are
+ - ms: milliseconds
+ - s: seconds (1000 milliseconds)
+ - m: minutes (60,000 milliseconds)
+ - h: hours (3,600,000 milliseconds)
+
[String]: /core/Types/String
[Array.filter]: /core/Types/Array#Array:filter
+[Function.delay]: /core/Types/Function#Function:delay
[encodeURIComponent]: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent
View
18 Source/Types/String.Extras.js
@@ -79,7 +79,16 @@ tidy = {
'-': /[\u2013]/g,
// '--': /[\u2014]/g,
'»': /[\uFFFD]/g
-};
+},
+
+conversions = {
+ ms: 1,
+ s: 1000,
+ m: 6e4,
+ h: 36e5
+},
+
+findUnits = /(\d*.?\d+)([msh]+)/;
var walk = function(string, replacements){
var result = string, key;
@@ -141,6 +150,13 @@ String.implement({
if (trail) string += trail;
}
return string;
+ },
+
+ ms: function(){
+ // "Borrowed" from https://gist.github.com/1503944
+ var units = findUnits.exec(this);
+ if (units == null) return Number(this);
+ return Number(units[1]) * conversions[units[2]];
}
});
View
31 Tests/Specs/1.3/Types/String.Extras.js
@@ -70,3 +70,34 @@ describe('String.truncate', function(){
});
});
+
+describe('String.ms', {
+
+ 'should convert seconds to milliseconds': function(){
+ expect('5s'.ms()).toEqual(5000);
+ },
+
+ 'should convert minutes to milliseconds': function(){
+ expect('2m'.ms()).toEqual(12e4);
+ },
+
+ 'should convert hours to milliseconds': function(){
+ expect('3h'.ms()).toEqual(108e5);
+ },
+
+ 'should keep milliseconds as milliseconds': function(){
+ expect('250ms'.ms()).toEqual(250);
+ },
+
+ 'should treat no unit as milliseconds': function(){
+ expect('100'.ms()).toEqual(100);
+ },
+
+ 'should return NaN for unknown units': function(){
+ jasmine.Matchers.prototype.toBeNaN = function(){
+ return isNaN(this.actual);
+ };
+ expect('30q').toBeNaN();
+ }
+
+});
Please sign in to comment.
Something went wrong with that request. Please try again.