Skip to content

Instantly share code, notes, and snippets.

@AstakhovArtem
Last active September 2, 2016 20:57
Show Gist options
  • Save AstakhovArtem/4872c1e5aa2224bbb1a8c27b8822f454 to your computer and use it in GitHub Desktop.
Save AstakhovArtem/4872c1e5aa2224bbb1a8c27b8822f454 to your computer and use it in GitHub Desktop.
const Prom = (function () {
function toArray(arr){
return (
(Array.isArray(arr) && arr)
|| (!Array.isArray(arr) && arr.length && [].slice.call(arr))
|| (typeof arr === 'string' && arr.split(''))
|| (typeof arr === 'object' && [])
)
}
function getRest(arrOrString){
return toArray(arrOrString).slice(1);
}
function _curry(fn) {
let args = getRest(toArray(arguments));
return function () {
return fn.apply(this, args.concat(toArray(arguments)));
};
}
function curry(fn, length) {
length = length || fn.length;
return function () {
let combined = [fn].concat(toArray(arguments));
return arguments.length < length ?
length - arguments.length > 0
? curry(_curry.apply(this, combined), length - arguments.length)
: _curry.call(this, combined )
: fn.apply(this, arguments);
};
}
function Promise (callback) {
this._panding = [];
this._isNestedPromise = false;
this._compose = function () {
let args = [].slice.call(arguments);
return function() {
let _arguments = arguments;
return args.reverse().reduce((cur, next) => {
if (cur instanceof Promise || this._isNestedPromise) {
this._isNestedPromise = true;
cur._panding.push(next);
} else {
return cur ? next.call(next, cur) : next.apply(next, _arguments);
}
}, 0);
}.bind(this)
};
this._resolve = function (data) {
this._compose.apply(this, this._panding.reverse())(data);
this._panding = [];
}.bind(this);
this._reject = function () {}.bind(this);
this.then = function (cb) {
this._panding.push(cb);
return this;
};
this.catch = function () {
return this;
};
callback(this._resolve, this._reject);
}
Promise.race = function (arrayOfPromices) {
return new Promise(function (resolve, reject) {
let curredResolve = curry(resolve, 1);
arrayOfPromices.forEach(function (item) {
item.then(curredResolve);
});
});
}
return Promise;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment