import {Notebook} from "./notebooks"; export module NotebookTransformers { /** * Returns true if a notebook has a module, that has a variable with name == cellName * @param notebook * @param cellName */ export function hasCell(notebook: Notebook, cellName: string) : boolean { return notebook.modules.some(m => m.variables.some(v => v.name == cellName)); } /** * Replaces a named variable in the notebook with a new value. * * Pass true for appendIfNotFound to append the variable if it isn't already in the notebook - this is useful to override * libraries built into the @observable/runtime * * Returns undefined if the variable isn't found and appendIfNotFound == false * * @param notebook * @param variableName * @param newValue * @param inputs * @param appendIfNotFound */ export function setNotebookVariable(notebook: Notebook, variableName: string, newValue: ((...args:any[]) => any), inputs: string[]|undefined = undefined, appendIfNotFound: boolean = false) : Notebook|undefined { // clones notebook but replaces the variable referred to by variableName with a newValue // care has been taken in this function that it doesn't modify the original notebook if (hasCell(notebook, variableName)) { let varNotFound = true; const modules = notebook.modules.map((m) => { const variables = m.variables.map((v) => { if (varNotFound && v.name === variableName) { let changes: {value: any, inputs?: any} = {value: newValue}; if (inputs !== undefined) { changes.inputs = inputs; } return Object.assign({}, v, changes); } return v; }); return Object.assign({}, m, {variables}) }); return Object.assign({}, notebook, {modules}); } else if (appendIfNotFound) { console.log('appending'); let variable = { name: variableName, inputs, value: newValue }; const modules = notebook.modules.map(m => { let variables = m.variables.map(v => Object.assign({}, v)); return Object.assign({}, m, {variables}); }); modules[modules.length - 1].variables.push(variable); return Object.assign({}, notebook, {modules}); } return undefined; } }