diff --git a/src/js-function/__tests__/onestho.test.ts b/src/js-function/__tests__/onestho.test.ts new file mode 100644 index 0000000..0acbdad --- /dev/null +++ b/src/js-function/__tests__/onestho.test.ts @@ -0,0 +1,20 @@ +import * as OneShot from '../oneshot'; + +test('sum function', () => { + expect(OneShot.sum(1, 2)).toEqual(3); + expect(OneShot.sum(2, 2)).toEqual(4); + expect(OneShot.sum(-1, -6)).toEqual(-7); + expect(OneShot.sum(-5, 5)).toEqual(0); +}); + +test('引数を1つだけ受け取る関数', () => { + // @ts-ignore + global.x = 10; + expect(OneShot.argFunction(0)).toEqual(10); +}); + +test('globalな値をそのまま返す関数', () => { + // @ts-ignore + global.y = 10; + expect(OneShot.simpleReturnFunction()()).toEqual(10); +}); diff --git a/src/js-function/oneshot.ts b/src/js-function/oneshot.ts new file mode 100644 index 0000000..316801f --- /dev/null +++ b/src/js-function/oneshot.ts @@ -0,0 +1,7 @@ +export const sum = new Function('a', 'b', 'return a + b;'); + +export const argFunction = new Function('a', 'return a + x;'); + +export const simpleReturnFunction = () => { + return new Function('return y;'); +}; diff --git a/src/react-function/__tests__/oneshot.test.tsx b/src/react-function/__tests__/oneshot.test.tsx new file mode 100644 index 0000000..078f527 --- /dev/null +++ b/src/react-function/__tests__/oneshot.test.tsx @@ -0,0 +1,6 @@ +import * as OneShot from '../oneshot'; + +test.skip('StringからFunctionを生成する', () => { + const maker = OneShot.createComponent(); + expect(maker()).toEqual(OneShot.MyComponent); +}); diff --git a/src/react-function/oneshot.tsx b/src/react-function/oneshot.tsx index eaea640..896814b 100644 --- a/src/react-function/oneshot.tsx +++ b/src/react-function/oneshot.tsx @@ -1,21 +1,15 @@ -// @ts-ignore -import * as transformJSX from '@babel/plugin-transform-react-jsx'; -// @ts-ignore -import * as babel from '@babel/standalone'; import * as React from 'react'; -const parse = (raw: string): string | null => - babel.transform(raw, { - plugins: [transformJSX], - }).code; +export interface MyComponentProps { + text: string; +} -const wrap = (jsx: string) => `${jsx}`; +export class MyComponent extends React.Component { + public render() { + return
${this.props.text}
; + } +} -export const toComponent = (jsx: string) => { - const el = parse(wrap(jsx)); - const keys = Object.keys(scope); - const values = keys.map((key) => scope[key]); - const createFunction = new Function('React', ...keys, `return props => ${el}`); - const Comp = createFunction(React, ...values); - return Comp; -}; +export function createComponent() { + return new Function('React', 'MyComponent', `return props => ${MyComponent}`); +} \ No newline at end of file diff --git a/src/styled-components/oneshot.tsx b/src/styled-components/oneshot.tsx index 4cf71ff..b07ae7c 100644 --- a/src/styled-components/oneshot.tsx +++ b/src/styled-components/oneshot.tsx @@ -7,7 +7,7 @@ export const createExample = () => { body { font-family: sans-serif; } - `; + ]`; const Title = styled.h1` font-size: 1.5em;