constructor() { this.called = false; this.deferred = defer(); const og = this.call; this.call = mem((...args) => { this.called = true; return og.call(this, args); }); }
const decrypt = (params, opts) => { if (!decryptFn) { decryptFn = pify(kms.decrypt.bind(kms)); if (opts.maxAge && opts.maxAge > 0) { // If `maxAge` is provided, use memoization decryptFn = mem(decryptFn, {maxAge: opts.maxAge}); } } return decryptFn(params); };
function Evaluator (opts) { if (!(this instanceof Evaluator)) return new Evaluator(opts) opts = opts || {} var compare if (opts.cache !== false) { var _includes = memoize(includes, opts.cacheOpts) if (!opts.insensitive) { compare = createSensitiveCompare(_includes) } else { var _lowercase = memoize(lowercase, opts.cacheOpts) compare = createInsensitiveCompare(_includes, _lowercase) } } else { compare = opts.insensitive ? createInsensitiveCompare(includes, lowercase) : createSensitiveCompare(includes) } this.visit_var = compare this.visit_and = function (node, vars) { return this.evaluate(node.left, vars) && this.evaluate(node.right, vars) } this.visit_or = function (node, vars) { return this.evaluate(node.left, vars) || this.evaluate(node.right, vars) } this.visit_not = function (node, vars) { return !this.evaluate(node.operand, vars) } this.evaluate = function (node, vars) { return node.accept(this, vars) } }
import { Users } from '../../../models'; import { settings } from '../../../settings'; import memoize from 'mem'; const maxAgeInMS = 1000; const getUserByUsername = (username) => Users.findOneByUsername(username, { fields: { name: 1 } }); const getNameOfUser = memoize((username) => { const user = getUserByUsername(username); return user ? user.name : undefined; }, { maxAge: maxAgeInMS }); export const composeMessageObjectWithUser = function(message, userId) { if (message) { if (message.starred && Array.isArray(message.starred)) { message.starred = message.starred.filter((star) => star._id === userId); } if (settings.get('UI_Use_Real_Name')) { if (message.u && message.u._id) { message.u.name = getNameOfUser(message.u.username); } if (message.mentions && message.mentions.length) { message.mentions.forEach((mention) => mention.name = getNameOfUser(mention.username)); } if (message.reactions && Object.keys(message.reactions).length) { Object.keys(message.reactions).forEach((reaction) => { const names = message.reactions[reaction].usernames.map(getNameOfUser); message.reactions[reaction].names = names; }); } }
} function getWinLocaleSync() { const stdout = execa.sync('wmic', ['os', 'get', 'locale']).stdout; const lcidCode = parseInt(stdout.replace('Locale', ''), 16); return lcid.from(lcidCode); } module.exports = mem(opts => { opts = opts || defaultOpts; const envLocale = getEnvLocale(); let thenable; if (envLocale || opts.spawn === false) { thenable = Promise.resolve(getLocale(envLocale)); } else if (process.platform === 'win32') { thenable = getWinLocale(); } else { thenable = getUnixLocale(); } return thenable.then(locale => locale || defaultLocale) .catch(() => defaultLocale); }); module.exports.sync = mem(opts => { opts = opts || defaultOpts; const envLocale = getEnvLocale(); let res; if (envLocale || opts.spawn === false) { res = getLocale(envLocale);
} function cleanWinCmd(x) { return x.replace(/^.*\\/, ''); } function noop() {} module.exports = mem(() => { const envVar = getEnvVar(); if (envVar) { return Promise.resolve(envVar); } if (process.platform === 'darwin' || process.platform === 'linux') { return execa('id', ['-un']).then(x => x.stdout).catch(noop); } else if (process.platform === 'win32') { return execa('whoami').then(x => cleanWinCmd(x.stdout)).catch(noop); } return Promise.resolve(); }); module.exports.sync = mem(() => { const envVar = getEnvVar(); if (envVar) { return envVar; }
const fullname = (res.stdout.split(':')[4] || '').replace(/,.*/, ''); return fullname || Promise.reject(); }); } function fallback() { if (process.platform === 'darwin') { return pAny([checkPasswd(), checkOsaScript()]); } if (process.platform === 'win32') { // Fullname is usually not set by default in the system on Windows 7+ return pAny([checkGit(), checkWmic()]); } return pAny([checkPasswd(), checkGetEnt(), checkGit()]); } function getFullName() { return checkEnv() .catch(checkAuthorName) .catch(fallback) .catch(() => {}); } module.exports = mem(getFullName, { cacheKey() { return JSON.stringify(filterObj(process.env, envVars)); } });
import mem from "mem" let keepEscaped = str => str.startsWith("\\") ? str.slice(1) : "" let dropComments = str => str.replace(/\\?#.*$|\s+/gm, keepEscaped) let processExt = mem(raw => raw.map(dropComments)) let escapeMeta = str => str.replace(/[|{}[\]()?+*.\\$^]/g, "\\$&") let toString = val => { if (val == null) return "" if (val[Symbol.match]) return val.source return typeof val != "string" && typeof val[Symbol.iterator] == "function" ? Array.from(val, toString).join("|") : escapeMeta(`${val}`) } export default mem(flags => { let ext = flags.includes("x") if (ext) flags = flags.replace("x", "") return ({ raw }, ...vals) => { if (ext) raw = processExt(raw) let pattern = String.raw({ raw }, ...vals.map(toString)) return new RegExp(pattern, flags) }
import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { Subscriptions, Messages } from '../../../models'; import { callbacks } from '../../../callbacks'; import { settings } from '../../../settings'; import { hasAtLeastOnePermission } from '../../../authorization'; import { CachedCollectionManager } from '../../../ui-cached-collection'; import _ from 'underscore'; import mem from 'mem'; export const AutoTranslate = { findSubscriptionByRid: mem((rid) => Subscriptions.findOne({ rid })), messageIdsToWait: {}, supportedLanguages: [], getLanguage(rid) { let subscription = {}; if (rid) { subscription = this.findSubscriptionByRid(rid); } const language = (subscription && subscription.autoTranslateLanguage) || Meteor.user().language || window.defaultUserLanguage(); if (language.indexOf('-') !== -1) { if (!_.findWhere(this.supportedLanguages, { language })) { return language.substr(0, 2); } } return language; }, translateAttachments(attachments, language) { for (const attachment of attachments) {
import mem from 'mem'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { ChatSubscription } from '../../app/models'; import { roomTypes } from '../../app/utils'; import { call } from '../../app/ui-utils'; const getRoomById = mem((rid) => call('getRoomById', rid)); FlowRouter.goToRoomById = async (rid) => { if (!rid) { return; } const subscription = ChatSubscription.findOne({ rid }); if (subscription) { return roomTypes.openRouteLink(subscription.t, subscription, FlowRouter.current().queryParams); } const room = await getRoomById(rid); return roomTypes.openRouteLink(room.t, room, FlowRouter.current().queryParams); };
const COURSE_URL = APP_BASE + 'courseData.url' const AREA_URL = APP_BASE + 'areaData.url' const actions = { notifications: notificationActions, } const worker = new LoadDataWorker() let fetchText = (...args) => fetch(...args) .then(status) .then(text) const memFetchText: typeof fetchText = mem(fetchText) worker.addEventListener('error', msg => console.warn('[main] received error from load-data worker:', msg), ) worker.addEventListener('message', ({data}: {data: string}) => { let {type, message}: DispatchMessage = JSON.parse(data) if (type === 'dispatch') { const action = actions[message.type][message.action](...message.args) global._dispatch && global._dispatch(action) } }) export type DispatchMessage = { type: 'dispatch',
import fsWriteStreamAtomic from 'fs-write-stream-atomic'; import getRes from 'get-res'; import logSymbols from 'log-symbols'; import mem from 'mem'; import mkdirp from 'mkdirp'; import rimraf from 'rimraf'; import screenshotStream from 'screenshot-stream'; import viewportList from 'viewport-list'; import protocolify from 'protocolify'; import arrayUniq from 'array-uniq'; import filenamifyUrl from 'filenamify-url'; import template from 'lodash.template'; import pify from 'pify'; import plur from 'plur'; const getResMem = mem(getRes); const viewportListMem = mem(viewportList); let listener; /** * Fetch ten most popular resolutions * * @param {String} url * @param {Object} options * @api private */ export async function resolution(url, options) { for (const item of await getResMem()) { this.sizes.push(item.item);
import { Blaze } from 'meteor/blaze'; import { ChatMessage, ChatSubscription, ChatRoom } from '../../../models'; import { getConfig } from '../config'; import { RoomManager } from './RoomManager'; import { readMessage } from './readMessages'; import { renderMessageBody } from './renderMessageBody'; export const normalizeThreadMessage = mem((message) => { if (message.msg) { return renderMessageBody(message).replace(/<br\s?\\?>/g, ' '); } if (message.attachments) { const attachment = message.attachments.find((attachment) => attachment.title || attachment.description); if (attachment && attachment.description) { return s.escapeHTML(attachment.description); } if (attachment && attachment.title) { return s.escapeHTML(attachment.title); } } }, { maxAge: 1000 }); export const upsertMessage = ({ msg: { _id, ...msg }, subscription }) => { const userId = msg.u && msg.u._id; if (subscription && subscription.ignored && subscription.ignored.indexOf(userId) > -1) { msg.ignored = true; }
}) => React.Node, groupBy: GROUP_BY_KEY, sortBy: SORT_BY_KEY, limitTo: string, filterBy: string, } type State = {| error: ?string, inProgress: boolean, didSearch: boolean, results: List<CourseType>, grouped: List<string | CourseType>, |} const memSortAndGroup: typeof sortAndGroup = mem(sortAndGroup, {maxAge: 10000}) export class Querent extends React.Component<Props, State> { state = { error: '', inProgress: false, results: List(), grouped: List(), didSearch: false, } _isMounted: boolean = false componentDidMount() { this._isMounted = true