How to use moize - 10 common examples

To help you get started, we’ve selected a few moize examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ehmicky / log-process-errors / src / main.js View on Github external
const addListener = function({ opts, name, eventFunc }) {
  // `previousEvents` is event-name-specific so that if events of a given event
  // stopped being emitted, others still are.
  // `previousEvents` can take up some memory, but it should be cleaned up
  // by `removeListener()`, i.e. once `eventListener` is garbage collected.
  const previousEvents = new Set()
  // Should only emit the warning once per event name and per `init()`
  const mEmitLimitedWarning = moize(emitLimitedWarning)

  const eventListener = eventFunc.bind(null, {
    opts,
    name,
    previousEvents,
    mEmitLimitedWarning,
  })
  process.on(name, eventListener)

  return { eventListener, name }
}
github ehmicky / log-process-errors / gulp / utils / localpack-code / root.js View on Github external
const pkgDir = require('pkg-dir')
const moize = require('moize').default

// Retrieve package root directory
const getPackageRoot = async function(cwd) {
  const packageRoot = await pkgDir(cwd)

  assert(
    packageRoot !== null,
    'The root directory of this package was not found',
  )

  return packageRoot
}

const mGetPackageRoot = moize(getPackageRoot)

module.exports = {
  getPackageRoot: mGetPackageRoot,
}
github ehmicky / log-process-errors / gulp / utils / get-versions / range.js View on Github external
}

// `opts.range` defaults to `engines.node` field in `package.json`
const getDefaultRange = function() {
  const packageRoot = pkgDir.sync()

  if (packageRoot === null) {
    return
  }

  // eslint-disable-next-line import/no-dynamic-require
  const { engines: { node } = {} } = require(`${packageRoot}/package.json`)
  return node
}

const mGetDefaultRange = moize(getDefaultRange)

const normalizeRange = function({ range }) {
  const rangeA = validRange(range)
  assert(rangeA !== null, `Invalid Node.js versions range: ${range}`)
  return rangeA
}

// Filter releases using `opts.range` and only keep major releases that have
// at lease one minor/patch release.
const applyOnMajorReleases = function({ majorReleases, range }) {
  return majorReleases
    .map(majorRelease => applyOnMajorRelease({ majorRelease, range }))
    .filter(hasReleases)
}

const applyOnMajorRelease = function({
github ehmicky / log-process-errors / gulp / utils / get-versions / all.js View on Github external
// eslint-disable-next-line import/no-internal-modules
const RELEASE_SCHEDULE = require('node-releases/data/release-schedule/release-schedule')
const { major, minor } = require('semver')
const moize = require('moize').default

// Retrieve all Node.js releases, grouped by major release.
// Major release also indicate:
//  - whether they are currently supported
//  - whether they are/were LTS
const getAllMajorReleases = function() {
  return Object.entries(RELEASE_SCHEDULE)
    .map(normalizeMajorRelease)
    .filter(hasReleases)
}

const mGetAllMajorReleases = moize(getAllMajorReleases)

const normalizeMajorRelease = function([
  majorVersion,
  { start, end, codename },
]) {
  // Strip 'v' from version
  const majorVersionA = majorVersion.slice(1)

  const supported = isSupported({ start, end })
  const lts = codename !== undefined
  const releases = getReleases({ majorVersion: majorVersionA })

  return { majorVersion: majorVersionA, supported, lts, releases }
}

// Check if Node.js is currently supporting this version
github anywhichway / nano-memoize / benchmark / index.js View on Github external
const runSingleParameterSuite = () => {
  const fibonacciSuite = new Benchmark.Suite('Single parameter');
  const fibonacciNumber = 35;

  const mUnderscore = underscore(fibonacci);
  const mLodash = lodash(fibonacci);
 // const mRamda = ramda(fibonacci);
  const mMemoizee = memoizee(fibonacci);
  const mFastMemoize = fastMemoize(fibonacci);
  const mAddyOsmani = addyOsmani(fibonacci);
  const mMemoizerific = memoizerific(Infinity)(fibonacci);
  const mLruMemoize = lruMemoize(Infinity)(fibonacci);
  const mMoize = moize(fibonacci);
  const mMicroMemoize = microMemoize(fibonacci);
  const mIMemoized = iMemoized.memoize(fibonacci);
  const mNano = nanomemoize(fibonacci);


  return new Promise((resolve) => {
    fibonacciSuite
	    .add('nano-memoize', () => {
	    	mNano(fibonacciNumber);
	    })
      .add('addy-osmani', () => {
        mAddyOsmani(fibonacciNumber);
      })
      .add('lodash', () => {
        mLodash(fibonacciNumber);
      })
github ehmicky / autoserver / src / serverinfo / main.js View on Github external
import { getHostInfo } from './host.js'
import { getVersionsInfo } from './versions.js'
import { getProcessInfo } from './process.js'

// Retrieve process-specific and host-specific information
const mGetServerinfo = function({ config: { name: processName } = {} }) {
  const host = getHostInfo()
  const versions = getVersionsInfo()
  const processInfo = getProcessInfo({ host, processName })

  return { host, versions, process: processInfo }
}

// Speed up memoization because serializing `config` is slow
export const getServerinfo = moize(mGetServerinfo, { transformArgs: () => pid })
github ehmicky / autoserver / src / rpc / adapters / graphql / load / types / object / main.js View on Github external
return type
}

// Memoize object type constructor in order to infinite recursion.
// We use the type name, i.e.:
//  - type name must differ everytime type might differ
//  - in particular, at the moment, type name differ when inputObjectType
//    or command changes
// We also namespace with a UUID which is unique for each new call to
// `getGraphqlSchema()`, to avoid leaking
const transformArgs = function([def, opts]) {
  const typeName = getTypeName({ def, opts })
  return `${opts.graphqlSchemaId}/${typeName}`
}

export const graphqlObjectTGetter = moize(mGraphqlObjectTGetter, {
  transformArgs,
})
github ehmicky / autoserver / src / validation / custom_validator.js View on Github external
import { getModelParams } from '../functions/params/values.js'

import { getValidator } from './validator.js'

// Add custom validation keywords, from config.validation
const mGetCustomValidator = function({ config: { validation = {} } = {} }) {
  const validator = getValidator()
  return Object.entries(validation).reduce(addCustomKeyword, validator)
}

// Serializing the whole config as is too slow, so we just take keywords list.
const transformArgs = function([{ config: { validation = {} } = {} }]) {
  return Object.keys(validation).join(',')
}

export const getCustomValidator = moize(mGetCustomValidator, { transformArgs })

const addCustomKeyword = function(
  validatorA,
  [keyword, { test: testFunc, message, type }],
) {
  // We name `null` `empty` in config, as it is more YAML-friendly
  const typeA = type === 'empty' ? 'null' : type

  validateCustomKeyword({ type: typeA, keyword })

  const validate = keywordFunc({ keyword, testFunc, message })
  const validatorB = validatorA.addKeyword(keyword, {
    validate,
    type: typeA,
    $data: true,
  })
github hashicorp / nomad / website / .yalc / @hashicorp / react-docs-page / server.js View on Github external
import fs from 'fs'
import path from 'path'
import validateFilePaths from '@hashicorp/react-docs-sidenav/utils/validate-file-paths'
import validateRouteStructure from '@hashicorp/react-docs-sidenav/utils/validate-route-structure'
import validateUnlinkedContent from '@hashicorp/react-docs-sidenav/utils/validate-unlinked-content'
import {
  loadVersionList,
  loadVersionedDocument,
  loadVersionedNavData,
  getVersionFromPath,
} from '@hashicorp/versioned-docs/server'
import moize from 'moize'
import { normalizeVersion } from '@hashicorp/versioned-docs/client'
import renderPageMdx from './render-page-mdx'

const cachedLoadVersionNavData = moize(loadVersionedNavData)

// So far, we have a pattern of using a common value for
// docs catchall route parameters: route/[[...page]].jsx.
// This default parameter ID captures that pattern.
// It can be overridden via options.
const DEFAULT_PARAM_ID = 'page'

async function generateStaticPaths({
  navDataFile,
  localContentDir,
  paramId = DEFAULT_PARAM_ID,
  product,
  basePath,
  currentVersion,
}) {
  let navData
github aduth / memize / benchmark / index.js View on Github external
const runMultiplePrimitiveSuite = () => {
	const fibonacciSuite = new Benchmark.Suite( 'Multiple parameters (Primitive)' );
	const fibonacciNumber = 35;
	const isComplete = false;

	const mMemoizee = memoizee( fibonacciMultiplePrimitive );
	const mFastMemoize = fastMemoize( fibonacciMultiplePrimitive );
	const mMemoizejs = memoizejs( fibonacciMultiplePrimitive );
	const mMemoizerific = memoizerific( Infinity )( fibonacciMultiplePrimitive );
	const mLruMemoize = lruMemoize( Infinity )( fibonacciMultiplePrimitive );
	const mMoize = moize( fibonacciMultiplePrimitive );
	const mMoizeSerialize = moize.serialize( fibonacciMultiplePrimitive );
	const mMemize = memize( fibonacciMultiplePrimitive );

	return new Promise( ( resolve ) => {
		fibonacciSuite
			.add( 'memoizee', () => {
				mMemoizee( fibonacciNumber, isComplete );
			} )
			.add( 'fast-memoize', () => {
				mFastMemoize( fibonacciNumber, isComplete );
			} )
			.add( 'memoizejs', () => {
				mMemoizejs( fibonacciNumber, isComplete );
			} )
			.add( 'memoizerific', () => {
				mMemoizerific( fibonacciNumber, isComplete );

moize

Blazing fast memoization based on all parameters passed

MIT
Latest version published 2 years ago

Package Health Score

59 / 100
Full package analysis