license import { ENGINE } from '../engine' ; import { isPromise } from '../util' ; export const OP_SCOPE_SUFFIX = '__op' ; /**
 * Used for wrapping functions that perform math operations on
 * Tensors. The function will be wrapped in a named scope that cleans all
 * memory usage after the function is done.
 */ export function op < T extends Function > ( f ) { const keys = Object . keys ( f ) ; if ( keys . length !== 1 ) { throw new Error ( `Please provide an object with a single key ` + `(operation name) mapping to a function. Got an object with ` + `${ keys . length } keys.` ) ; } let opName = keys [ 0 ] ; const fn = f [ opName ] ; if ( opName . endsWith ( '_' ) ) { opName = opName . substring ( 0 , opName . length - 1 ) ; } opName = opName + OP_SCOPE_SUFFIX ; const f2 = ( ... args ) => { ENGINE . startScope ( opName ) ; try { const result = fn ( ... args ) ; if ( isPromise ( result ) ) { console . error ( 'Cannot return a Promise inside of tidy.' ) ; } ENGINE . endScope ( result ) ; return result ; } catch ( ex ) { ENGINE . endScope ( null ) ; throw ex ; } } ; Object . defineProperty ( f2 , 'name' , { value : opName , configurable : true } ) ; return f2 as any as T ; }