var methodBody = function() { var argsLength = arguments.length; var args = new Array(argsLength); for (var i = 0; i < argsLength; i++) { args[i] = arguments[i]; } var requiredParamsStart = apiPathParamsCount; var requiredParamsEnd = requiredParamsStart + paramNames.length; var requiredParamArgs = args.slice(requiredParamsStart, requiredParamsEnd); // Callback is at the end var callback = isFunction(args[args.length - 1]) ? args.pop() : null; // Required Parmas var params = zipObject(paramNames, requiredParamArgs); extend(params, isPlainObject(args[args.length - 1]) ? args.pop() : {}); // Path arguments are determined after required parameters var apiPathArgs = args.slice(0, apiPathParamsCount); var request = requestType; if (isString(requestType)) { request = requestType.toUpperCase() === 'POST' ? client.postRequest : client.getRequest; } else if (!isFunction(requestType)) { request = client.getRequest; } return request.call(client, buildApiPath(apiPathArgs), params, callback); };
/** * 获取指定唯一标识的日报。 * @param String p_id 指定的唯一标识。 * @param {Function(err, res)} [p_callback] */ static getStory(p_id, p_callback) { if (isFunction(p_callback)) { if (isEmpty(trim(p_id))) { if (isFunction(p_callback)) { p_callback("p_id must not be null"); } } else { return $.get(`/api/4/news/${p_id}`, (p_data) => { DailyManager._stories[p_id] = p_data; p_callback(null, p_data); }).fail(() => { p_callback("/api/4/news/ error"); }); } } return null; }
test('disable/enable', assert => { assert.plan(10); const signal = src(); let trigger = 0; const fn = () => { trigger += 1; }; signal.on('foo', fn); signal.trigger('foo'); assert.ok(isFunction(signal.disable), `disable is a function`); assert.ok(isFunction(signal.enable), `enable is a function`); assert.is(trigger, 1, `can trigger an event`); assert.doesNotThrow(() => signal.disable(), `disable doesn't throw`); assert.doesNotThrow(() => signal.disable(), `calling disable multiple times doesn't throw`); assert.doesNotEqual(() => signal.trigger('foo'), `calling a disabled signal doesn't throw`); assert.is(trigger, 1, `when disabled, the event is not called`); assert.doesNotThrow(() => signal.enable(), `enable doesn't throw`); assert.doesNotThrow(() => signal.enable(), `calling enable multiple times doesn't throw`); signal.trigger('foo'); assert.is(trigger, 2, `when re-enabled, the event is called`); assert.end(); });
(res, val) => res && isPlainObject(val) && isString(val.name) && (isUndefined(val.label) || isString(val.label)) && (isUndefined(val.template) || isString(val.template) || isFunction(val.template)) && (isUndefined(val.transformData) || isFunction(val.transformData)),
const deepDiff = (prev, next, name) => { const notify = (type, status) => { console.group(name) console[type](`%c%s`, `font-weight: bold`, status) console.log(`%cbefore`, `font-weight: bold`, prev) console.log(`%cafter `, `font-weight: bold`, next) console.groupEnd() } const isRefEntity = isRequiredUpdateObject(prev) && isRequiredUpdateObject(next) if (!_isEqual(prev, next)) { const isFunc = _isFunction(prev) && _isFunction(next) if (isFunc) { if (prev.name === next.name) { notify(`warn`, `Value is a function. Possibly avoidable re-render?`) } } else if (isRefEntity) { const keys = _union(_keys(prev), _keys(next)) keys.forEach(key => deepDiff(prev[key], next[key], `${name}.${key}`)) } } else if (prev !== next) { notify(`error`, `Value did not change. Avoidable re-render!`) if (isRefEntity) { const keys = _union(_keys(prev), _keys(next)) keys.forEach(key => deepDiff(prev[key], next[key], `${name}.${key}`)) } } else if (prev === next && !isRefEntity) { notify(`error`, `Value did not change. Avoidable re-render!`) } }
export const deepDiff = (prev, next, name = null, notes) => { const isRefEntity = isReferenceEntity(prev) && isReferenceEntity(next) if (!_isEqual(prev, next)) { const isFunc = _isFunction(prev) && _isFunction(next) if (isFunc) { if (prev.name === next.name) { return notes.concat(`${name} (fn)`) } } else if (isRefEntity) { const keys = _union(_keys(prev), _keys(next)) const result = keys.reduce((acc, key) => deepDiff(prev[key], next[key], addPath(name, key), acc), []); return notes.concat(result.length == 0 ? name : result) } } else if (prev !== next) { if (isRefEntity) { const keys = _union(_keys(prev), _keys(next)) const result = keys.reduce((acc, key) => deepDiff(prev[key], next[key], addPath(name, key), acc), []); return notes.concat(result.length == 0 ? name : result) } else { return notes.concat(name) } } return notes }
function customComparison (a, b, key) { if (isFunction(a) && isFunction(b)) { return true } if (key === 'categories') { return true } }
const validScale = (scl) => { if (isFunction(scl)) { return (isFunction(scl.copy) && isFunction(scl.domain) && isFunction(scl.range)); } else if (typeof scl === "string") { return supportedScaleStrings.indexOf(scl) !== -1; } return false; };
/** * Implementation of inherited function. * * @example * // call objFunc, srcFunc * _.wrap(objFunc, _.wrap(srcFunc, wrapperFunction)); * * @module xblocks-core/utils/wrapperFunction * @param {function} [srcFunc] * @param {function} [objFunc] * @param {...*} args * @private */ export default function (srcFunc, objFunc, ...args) { if (isFunction(objFunc)) { objFunc.apply(this, args); } if (isFunction(srcFunc)) { srcFunc.apply(this, args); } }
return function (arg1, arg2, arg3, arg4) { if (_isFunction(defaultHandler)) { defaultHandler(arg1, arg2, arg3, arg4); } if (_isFunction(customizedHandler)) { customizedHandler(arg1, arg2, arg3, arg4); } };
/* extend() -> lazy inheritance without a proto extend({...}) -> lazy inheritance with a proto extend(Function) -> inheritance without a proto extend(Function, {}) -> inherit with a proto extend(Function, Function) -> inheritance with prototype function */ function _extendClass(ParentClass) { // this ctor is used when extend is not provided with a constructor function. function AnonymousClass() { ParentClass.apply(this, arguments); if (this.initialize) { this.initialize(); } } var args = Array.prototype.slice.call(arguments, 1); //var childOrProto = args[args.length-1]; var ChildClass; var mixins = []; // the first argument must be a Class constructor, otherwise we will use an anonymous ctor. var idx = 0; if (isFunction(args[0])) { ChildClass = args[0]; idx++; } else { ChildClass = AnonymousClass; } // the remaining arguments should be Objects used as a mixin for the created prototype // the last argument may be a prototype constructor function. for (; idx < args.length; idx++) { if (isFunction(args[idx])) { if (idx !== args.length-1) { throw new Error('Illegal use of Class.extend(): Prototype function must be last argument.'); } if (ChildClass.hasOwnProperty('Prototype')) { throw new Error('Class ' + ChildClass.name + ' has defined ' + ChildClass.name + '.Prototype which would be overwritten by Class.extend().\n' + 'You provided a prototype function when calling Class.extend().'); } else { ChildClass.Prototype = args[idx]; } break; } else if (isObject(args[idx])) { mixins.push(args[idx]); } else { throw new Error('Illegal use of Class.extend'); } } _inherit(ChildClass, ParentClass); // from right to left copy all mixins into the prototype // but never overwrite // like with lodash/extend, the mixin later in the args list 'wins' for (var i = mixins.length - 1; i >= 0; i--) { _mixin(ChildClass, mixins[i]); } return ChildClass; }
test('global', assert => { assert.plan(3); const signal = src; assert.ok(isFunction(signal.on), `signal is a singleton`); assert.ok(isFunction(signal.emit), `signal is a singleton`); assert.ok(signal[key], `signal has a Map`); assert.end(); });
test('factory', assert => { assert.plan(4); const signal = src; assert.ok(isFunction(signal), `signal is a factory`); assert.doesNotThrow(() => signal(), `signal can be called`); assert.ok(isFunction(signal()), `signal factory creates a factory`); assert.ok(isFunction(signal().on), `created signal has methods`); assert.end(); });
export default (event, socket, ack, isMiddleware = false) => (err) => { /* eslint-disable no-param-reassign */ debug('error occurred in "%s" :', event, err.message); if (!(err instanceof SocketEventError)) { debug('convert `err` into an instance of SocketEventError'); err = new SocketEventError(err.message || err, event, err.info, err.isPublic); } // if `isMiddleware` is `true`, then `ack` is actually `next` from `Namespace#use()` if (isFunction(ack) && isMiddleware) return ack(err); if (isFunction(ack)) ack(); socket.emit(emitEvent, err.data); };
function RP$callback(err, response, body) { /* jshint validthis:true */ var self = this; var origCallbackThrewException = false, thrownException; if (isFunction(self._rp_callbackOrig)) { try { self._rp_callbackOrig.apply(self, arguments); } catch (e) { origCallbackThrewException = true; thrownException = e; } } if (err) { self._rp_reject(assign(new errors.RequestError(err), { error: err, options: self._rp_options, response: response })); } else if (self._rp_options.simple && !(/^2/.test('' + response.statusCode))) { self._rp_reject(assign(new errors.StatusCodeError(response.statusCode, body), { error: body, options: self._rp_options, response: response })); } else { if (isFunction(self._rp_options.transform)) { try { self._rp_resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); } catch (e) { self._rp_reject(e); } } else if (self._rp_options.resolveWithFullResponse) { self._rp_resolve(response); } else { self._rp_resolve(body); } } if (origCallbackThrewException) { throw thrownException; } }
nest.test('- Props from empty store', test => { const store = createStore(() => ({ stash: {}, user: {} })); const wrapper = mountComponent(store); const stub = wrapper.find(Stub); test.ok(isFunction(stub.props().handleSubmit), 'handleSubmit is function'); test.ok(isFunction(stub.props().onInputChange), 'onInputChange is function'); const expected = {}; const actual = omit(stub.props(), ['handleSubmit', 'onInputChange']); test.deepEqual(actual, expected, 'props'); test.end(); });
const buildRoutes = routes => function(options = {}) { if (!isPlainObject(options)) { throw new TypeError( "Options for controller should be passed as plain JavaScript object, " + `but given value has type of ${getType(options)}.` ) } options = merge({}, defaults, options) for (const [name, route] of objectIterator.entries(routes)) { if (!isFunction(route.default)) { warn(`Controller "${name}" is not a function.`) continue } const prefix = name !== options.indexRoute ? `/${name}` : "" const Ctor = route.default r.use(prefix, new Ctor()) } return mountNonMatchedHandlers(r, options.nonMatched) }
const invariantReducer = (value, name) => { invariant( isUndefined(value) || isFunction(value), '%s should be a function', name ) }
Plan.__register = function (checks) { for (var key in checks) { if (!checks.hasOwnProperty(key) || !isFunction(checks[key])) { continue } if (chainingMethods && chainingMethods.indexOf(key) === -1) { continue } if (Plan.prototype[key]) { continue } Plan.prototype[key] = (function (fnName) { return function () { var self = this var args = Array.prototype.slice.call(arguments) return new Plan(function (that) { return that[fnName].apply(that, args) }, self, fnName) } })(key) } }
return _mapValues(links, function (value) { if (isFunction(value)) { return value(record, current, dest); } else { return value; } });
forEach(obj, (value, key) => { if (isObject(value) && !isFunction(value)) { newObj[key] = cloneDeep(value); } newObj[key] = value; });
return _mapValues(meta, function (value) { if (isFunction(value)) { return value(record, current); } else { return value; } });
function keyForAttribute(attribute) { if (isPlainObject(attribute)) { return _transform(attribute, function (result, value, key) { if (isComplexType(value)) { result[keyForAttribute(key)] = keyForAttribute(value); } else { result[keyForAttribute(key)] = value; } }); } else if (Array.isArray(attribute)) { return attribute.map(function (attr) { if (isComplexType(attr)) { return keyForAttribute(attr); } else { return attr; } }); } else { if (isFunction(opts.keyForAttribute)) { return opts.keyForAttribute(attribute); } else { return Inflector.caserize(attribute, opts); } } }
const error = function(err) { this.dispatch({ type: ERROR, err }); this.dispatch(actions.error(err)); if (options.error && isFunction(options.error)) { options.error(data); } }
render() { const { children, autoFrame, autoScroll, ScrollerNavigation } = this.props const scroll = this.connection return ( <ScrollerContainer> <ScrollerNavigation scroll={scroll} /> <ScrollerContent scrollRef={this.createRef} scroll={this.state.scroll} onScroll={this.handleScroll} onWheel={this.handleWheel} onTouchStart={this.handleTouchStart} onTouchMove={this.handleTouchMove} onTouchEnd={this.handleTouchEnd} > {isFunction(children) ? children(scroll) : children} </ScrollerContent> </ScrollerContainer> ) }
return function(blogIdentifier, params, callback) { params = extend({type: type}, params); if (isArray(validate)) { validate = partial(function(params, requireKeys) { if (requireKeys.length) { var keyIntersection = intersection(keys(params), requireKeys); if (requireKeys.length === 1 && !keyIntersection.length) { throw new Error('Missing required field: ' + requireKeys[0]); } else if (!keyIntersection.length) { throw new Error('Missing one of: ' + requireKeys.join(', ')); } else if (keyIntersection.length > 1) { throw new Error('Can only use one of: ' + requireKeys.join(', ')); } } return true; }, params, validate); } if (isFunction(validate)) { if (!validate(params)) { throw new Error('Error validating parameters'); } } if (arguments.length > 2) { return this.createPost(blogIdentifier, params, callback); } else { return this.createPost(blogIdentifier, params); } };
.then((channel) => { // eslint-disable-line no-unused-vars debug('unbanned', target._id); const result = {user, target}; if (isFunction(ack)) ack(result); socket.broadcast.to(socket.room).emit(broadcastEvent, result); return result; })
payload.meta = _mapValues(that.opts.meta, function (value) { if (isFunction(value)) { return value(records); } else { return value; } });
return _mapValues(links, function (value) { if (isFunction(value)) { return value(records); } else { return value; } });
TumblrClient.prototype.postRequest = function(apiPath, params, callback) { if (isFunction(params)) { callback = params; params = {}; } return postRequest(this.request.post, this.credentials, this.baseUrl, apiPath, this.requestOptions, params, callback); };