Last Updated: January 28, 2019
·
5.064K
· steveniseki

mout js introduction

<b>MOUT</b> or modular utilities is a collection of modular JavaScript utilities. It provides many helper methods similar to those found in other languages standard libraries. Consider it as a crossbrowser JavaScript standard library.

<b>Goals of moutjs</b>

increase code reuse;
Be clear (code should be clean/readable);
Be easy to debug;
Be easy to maintain;
Follow best practices;
Follow standards when possible;
Don't convert JavaScript into another language!
Be compatible with other frameworks;
Be modular;
Have unit tests for all modules;
Work on multiple environments (IE7+, modern browsers, node.js);

For full documentation visit: http://moutjs.com/

<b>Calling a method or module</b>

In mout you can require only a single method,a whole package, or the whole library:

// a single method
var append = require('mout/array/append');
var foo = ['a', 'b'], bar = ['b', 'd']; 
append(foo, bar); // ['a', 'b', 'b', 'd']

// a single package
var stringUtils = require('mout/string');
stringUtils.camelCase('Foo Bar'); // "fooBar"

// the whole lib
var mout = require('mout');
console.log( mout.math.clamp(17, 0, 10) ); // 10

mout contains the following packages:
<i>array, collection, date, function, lang, math, number, object, queryString, random, string and time.</i>

Here are some of the useful methods in these packages. These methods are some of my favorites, and not an extensive list. For full doumentation visit: http://moutjs.com/docs/

<b>array</b>

append(arr1, arr2):Array

var foo = ['a', 'b'], bar = ['b', 'd'];
append(foo, bar); // ['a', 'b', 'b', 'd']

combine(arr1, arr2):Array

var foo = ['a', 'b'], bar = ['b', 'd'];
combine(foo, bar); // ['a', 'b', 'd']

contains(arr, value):Boolean

var arr = [1, 2, 3];
contains(arr, 2);      // true

every(arr, callback, [thisObj]):Array #

var items = [1, 'foo', 'bar'];
every(items, isString);   // false
every(items, function(val, key, arr){
    return val != null;
}); // true

filter(arr, callback, [thisObj]):Array

var nums = [1, 2, 3, 4, 5, 6];
var oddNumbers = filter(nums, function(val, key, arr){
    return (val % 2) !== 0;
});
// > [1, 3, 5]

find(arr, callback, [thisObj]):*

vavar users = [
    {name:'steven', surname:'martin'},
    {name:'james', surname:'martin'}
];
// first item that matches name steven
find(arr, {name:'steven'}); // {name:'steven', surnname:'martin'}

forEach(arr, callback, [thisObj]):void

var items = ['foo', 'bar'];
forEach(items, function(val, key, arr){
    console.log(key +' : '+ val);
});

insert(arr, ...items):Number

var arr = ['a', 'b'];
insert(arr, 'a');       // 2 : ['a', 'b']

join(arr, [separator]):String

join(['a', 'b', 'c']); // 'abc'

map(arr, callback, [thisObj]]):Array

var src = ['lorem', 'ipsum', 'foo', 'amet'];
var lengths = map(src, 'length'); // [5, 5, 3, 4]

max(arr, [iterator], [thisObj]):*

max([10, 2, 7]); // 10

min(arr, [iterator], [thisObj]):*

min([10, 2, 7]); // 2

pick(arr, [nItems]):*

var arr = [1, 2, 3, 4, 5, 6];
var item1 = pick(arr); // 4, it picks a random value
var item2 = pick(arr); // 1, it picks a random value

pluck(arr, propName):Array

var users = [{name : 'John', age: 21}, {name: 'Jane', age : 27}];
var names = pluck(users, 'name'); // ["John", "Jane"]

remove(arr, item):void

var foo = [1, 2, 3, 4];
remove(foo, 2); // [1, 3, 4]

removeAll(arr, item):void

var foo = [1, 2, 3, 4, 2, 2];
removeAll(foo, 2); // [1, 3, 4];

shuffle(arr):Array

var arr = ['a', 'b', 'c', 'd', 'e'];
shuffle(arr); // ['b', 'd', 'e', 'c', 'a']

slice(arr, [start], [end]):Array

slice([1, 2, 3, 4], 1, 2); // [2, 3]

some(arr, callback, [thisObj]):Array

var items = [1, 'foo', 'bar'];
some(items, isString);   // true

sort(arr, [compareFn]):Array

sort([187, 23, 47, 987, 12, 59]); // [12, 23, 47, 59, 187, 987]
sort(['a', 'z', 'c', 'b']); // ['a', 'b', 'c', 'z']

union(...arrs):Array

var a = [1, 2], b = [3, 4];  // note: removes duplicates
union(a, b); // [1, 2, 3, 4]

<b>date</b>

dayOfTheYear(date):Number

dayOfTheYear(new Date(2013, 0, 1)); // 1

diff(date1, date2, [unitName]):Number #

var d1 = new Date(2012, 4, 5);
var d2 = new Date(2013, 4, 8);
diff(d1, d2);          // 31795200000
diff(d1, d2, 'hour');  // 8832
diff(d1, d2, 'week');  // 52.57142857142857

isSame(date1, date2[, period]):Boolean #

var date1 = new Date(2013, 1, 3);
var date2 = new Date(2013, 2, 9);
isSame(date1, date2);          // false
isSame(date1, date2, 'day');   // false
isSame(date1, date2, 'year');  // true

parseIso(str):Number #

parseIso('2000-01-02T20:10+04:00') // 946829400000

quarter(date):Number

quarter(new Date(2013, 1, 19)); // 1
quarter(new Date(2013, 4, 12)); // 2

strftime(date, format, [l10n]):String

var date = new Date(2013, 3, 8, 9, 2, 4);
strftime(date, '%Y-%m-%d'); // "2013-04-08" check docs for format

totalDaysInMonth(fullYear, monthIndex):Number

totalDaysInMonth(2008, 1); // 29 (leap year)
totalDaysInMonth(2009, 1); // 28

totalDaysInYear(fullYear):Number

totalDaysInYear(2009); // 365

weekOfTheYear(date, [firstDayOfWeek]):Number

weekOfTheYear( new Date(2013,0,9) ); // 1

<b>function</b>

awaitDelay(fn, delay):Function

var callback = after(onLoaded, 1000);
loadImages(callback);
function onLoaded(){
    console.log('loaded');
}

func(name):Function

// will call the method `getName()` for each `user`
var names = map(users, func('getName'));

<b>object</b>

contains(obj, value):Boolean

var obj = {
    a: 1,
    c: 2
};
contains(obj, 2);      // true

every(obj, callback, [thisObj]):Boolean

var obj = {
    a: 1,
    d: 'string'
};

every(obj, isNumber); // false

find(obj, callback, [thisObj])

var obj = {
    a: 'foo',
    b: 12
};

find(obj, isNumber); // 12

forIn(obj, callback[, thisObj])

function Foo(){
    this.foo = 1;
    this.bar = 2;
}

var obj = new Foo();
var result = 0, keys = [];

forIn(obj, function(val, key, o){
    result += val;
});

console.log(result); // 3

functions(obj):Array

var obj = {
    foo : function(){},
    bar : 'baz'
};
functions(obj); // ['foo']

get(obj, propName):*

var lorem = {
        ipsum : {
            dolor : {
                sit : 'amet'
            }
        }
    };

get(lorem, 'ipsum.dolor.sit'); // "amet"
get(lorem, 'foo.bar');         // undefined

has(obj, propName):Boolean

var animal = {
        cat : {
            claws : true
        }
    };

has(animal, 'cat');   // true

keys(obj):Array

var obj = {
    foo : 1,
    bar : 2,
    lorem : 3
};
keys(obj); // ['foo', 'bar', 'lorem']

pick(obj, ...keys):Object

var user = {
    firstName : 'John',
    lastName : 'Doe',
    gender : 'male'
};
// single or multiple paramaters     
pick(user, 'firstName', 'lastName'); // {firstName:"John", lastName: "Doe"}

pluck(obj, propName):Object

var users = {
    first: {
        name : 'John',
        age : 21
    },
    second: {
        name : 'Mary',
        age : 25
    }
};

pluck(users, 'age');  // {first: 21, second: 25} );

values(obj):Array

var obj = {
    foo : 1,
    bar : 2,
    lorem : 3
};
values(obj); // [1, 2, 3]

<b>string</b>

camelCase(str):String

camelCase('lorem-ipsum-dolor'); // "loremIpsumDolor"

contains(str, substring, [fromIndex]):Boolean

contains('lorem', 'or');  // true

crop(str, maxChars, [append]):String

crop('lorem ipsum dolor', 10);      // "lorem..."

endsWith(str, suffix):Boolean

endsWith('lorem ipsum', 'lorem'); // false

escapeHtml(str):String

escapeHtml('lorem & "ipsum"'); // "lorem &amp; &quot;ipsum&quot;"

unescapeHtml(str):String

unescapeHtml('lorem &amp; &quot;ipsum&quot;'); // 'lorem & "ipsum"'

escapeUnicode(str[, shouldEscapePrintable]):String

escapeUnicode('føo bår'); // > "f\u00f8o b\u00e5r"

unescapeUnicode(str):String

unescapeUnicode('\\u0066\\u00f8\\u006f\\u0020\\u0062\\u00e5\\u0072'); // > 'føo bår'

insert(str, index, partial):String

insert('foo', 100, 'bar'); // "foobar"

lpad(str, minLength[, char]):String
rpad(str, minLength[, char]):String

lpad('a', 5);        // "    a"
lpad('a', 5, '-');   // "----a"

ltrim(str, [chars]):String
rtrim(str, [chars]):String

ltrim('--lorem ipsum--', ['-']); // "lorem ipsum--"

makePath(...args):String

makePath('foo///bar/'); // "foo/bar/"

properCase(str):String

properCase('loRem iPSum'); // "Lorem Ipsum"

removeNonASCII(str):String

removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // "lorem-ipsum"

removeNonWord(str):String

removeNonWord('lorem ~!@#><., ipsum'); // "lorem - ipsum"

repeat(str, n):String

repeat('a', 3);  // "aaa"

stripHtmlTags(str):String

stripHtmlTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // "lorem ipsum"

startsWith(str, prefix):Boolean

startsWith('lorem ipsum', 'lorem'); // true

slugify(str[, delimeter]):String

var str = 'loremIpsum dolor spéçïãl chârs';
slugify(str, '_'); // "loremipsum_dolor_special_chars"

trim(str, [chars]):String

trim('   lorem ipsum   '); // "lorem ipsum"

truncate(str, maxChars, [append], [onlyFullWords]):String

truncate('lorem ipsum dolor', 11);             // "lorem ip..."

<b>queryString</b>

contains(url, paramName):Boolen

var url = 'example.com/?lorem=ipsum';
contains(url, 'lorem'); // true

decode(queryStr[, shouldTypecast]):Object

var query = '?foo=bar&lorem=123';
decode(query);        // {foo: "bar", lorem: 123}

encode(obj):String

encode({foo: "bar", lorem: 123}); // "?foo=bar&lorem=123"

getParam(url, param[, shouldTypecast]):*

var url = 'example.com/?foo=bar&lorem=123&ipsum=false';
getParam(url, 'lorem');        // 123

parse(url[, shouldTypecast]):Object

var url = 'example.com/?lorem=ipsum&a=123';
parse(url);        // {lorem: "ipsum", a: 123}

getQuery(url):String

getQuery('example.com/?lorem=ipsum'); // "?lorem=ipsum"

setParam(url, paramName, value):String

setParam('?lorem=1', 'foo', 123); // '?lorem=1&foo=123'

<b>random</b>

choice(...items):*

choice(1, 2, 3, 4, 5); // 3

guid():String

guid(); // 830e9f50-ac7f-4369-a14f-ed0e62b2fa0b

rand([min], [max]):Number

rand();      // 448740433.55274725
rand(0, 10); // 7.369723

randBool():Boolean

randBool(); // true

randHex([size]):String

randHex();   // "dd8575"

randInt([min], [max]):Number

randInt();      // 448740433

random():Number

random(); // 0.35435103671625257

<b>lang</b>

createObject(parent, [props]):Object

var base = {}; 
var myObj = createObject(base, {
    name : 'Lorem Ipsum'
}); // myObj inherits from base

is(x, y):Boolean

is(NaN, NaN); // true
is(-0, +0);   // false
is('a', 'b'); // false

isArguments(val):Boolean

isArray(val):Boolean

isBoolean(val):Boolean

isDate(val):Boolean

isFunction(val):Boolean

isInteger(val):Boolean

isNaN(val):Boolean

isNull(val):Boolean

isNumber(val):Boolean

isObject(val):Boolean

isString(val):Boolean

isUndefined(val):Boolean

toNumber(val):Number

toString(val):String

<b>math</b>

ceil(val[, step]):Number

ceil(7.2);   // 8

clamp(val, min, max):Number

clamp(13, 1, 10); // 10

floor(val[, step]):Number

floor(7.2);   // 7

inRange(val, min, max[, threshold]):Boolean

inRange( 5, 1, 10);    // true

<b>number</b>

currencyFormat(val[, nDecimalDigits, decimalSeparator, thousandsSeparator]):String

currencyFormat(1000);              // "1,000.00"

nth(n):String

nth(1); // "st"
nth(2); // "nd"

toInt(val):Number

toInt(1.25);   // 1

toUInt(val):Number

toUInt(1.25);                 // 1
toUInt(-0.55);                // 0

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside