Last active
December 25, 2015 17:59
-
-
Save nijikokun/7017057 to your computer and use it in GitHub Desktop.
is(value).a(Object) ? does('Nijiko').startWith('N') ? does([1,2,3]).endWith(3) ? does({ user: { name: 'Nijiko' } }).contain('user') ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Is / Does | |
* | |
* A poetic homage to Ruby. | |
* | |
* @author Nijiko Yonskai | |
* @license MIT | |
*/ | |
function is (value) { | |
return { | |
a: function (check) { | |
if (check.prototype) check = check.prototype.constructor.name; | |
var type = Object.prototype.toString.call(value).slice(8, -1).toLowerCase(); | |
return value !== undefined && value !== null && type === check.toLowerCase(); | |
}, | |
}; | |
} | |
function does (value) { | |
var arrayIndexOf = (Array.indexOf ? function (arr, obj, from) { | |
return arr.indexOf(obj, from); | |
} : function (arr, obj, from) { | |
var l = arr.length, i = from ? parseInt((1*from) + (from<0 ? l:0), 10) : 0; i = i<0 ? 0 : i; | |
for (; i<l; i++) if (i in arr && arr[i] === obj) return i; | |
return -1; | |
}); | |
return { | |
startWith: function (string) { | |
if (is(value).a(String)) return value.slice(0, string.length) == string; | |
if (is(value).a(Array)) return value[0] == string; | |
return false; | |
}, | |
endWith: function (string) { | |
if (is(value).a(String)) return value.slice(-string.length) == string; | |
if (is(value).a(Array)) return value[value.length - 1] == string; | |
return false; | |
}, | |
contain: function (field) { | |
if (is(value).a(String)) return value.indexOf(field) != -1; | |
if (is(value).a(Object)) return value.hasOwnProperty(field); | |
if (is(value).a(Array)) return !!~arrayIndexOf(value, field); | |
return false; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment