Created
October 30, 2016 15:28
-
-
Save syafdia/c26b4c25d23e4c08cd4af7a06856d683 to your computer and use it in GitHub Desktop.
Commonly used function in my JS project
This file contains 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
var utils = { | |
is: function (instanceOf, data) { | |
var dataType = Object.prototype.toString.call(data); | |
var expectedType = '[object ' + instanceOf + ']'; | |
return dataType === expectedType; | |
}, | |
isNot: function (instanceOf, data) { | |
return !this.is(instanceOf, data); | |
}, | |
get: function (path, obj) { | |
var _this = this; | |
var paths = path.split('.'); | |
var loop = function (o, ks) { | |
var k = ks.shift(); | |
if (!k || _this.isNot('Object', o)) { | |
return o; | |
} else { | |
if (o.hasOwnProperty(k)) { | |
return loop(o[k], ks); | |
} else { | |
return void 0; | |
} | |
} | |
}; | |
return loop(obj, paths); | |
}, | |
getOr: function (path, defaultVal, obj) { | |
return this.get(path, obj) || defaultVal; | |
}, | |
set: function (val, path, obj) { | |
var paths = path.split('.'); | |
var loop = function (o, ks) { | |
if (ks.length === 1) { | |
var k = ks.pop(); | |
o[k] = val; | |
return o; | |
} else { | |
var k = ks.shift(); | |
o[k] = loop({}, ks); | |
return o; | |
} | |
}; | |
loop(obj, paths); | |
}, | |
partial: function (f) { | |
if (this.isNot('Function', f)) { | |
var msg = 'First argument should be an instance of function'; | |
throw new TypeError(msg); | |
} | |
var args = Array.prototype.slice.call(arguments, 1); | |
return function () { | |
var argz = Array.prototype.slice.call(arguments); | |
return f.apply(this, args.concat(argz)); | |
} | |
}, | |
curry: function (f) { | |
if (this.isNot('Function', f)) { | |
var msg = 'Argument should be an instance of function'; | |
throw new TypeError(msg); | |
} | |
// TODO | |
}, | |
compose: function () { | |
// TODO | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment