总
之前看vue conf有人用vue组件算阶乘说图灵完备,于是突发奇想用组件做做二分?
Vue( 超栈了?Maximum call stack size exceeded
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <template> <demo v-if="this.l !== this.newl || this.r !== this.newr" :l="newl" :r="newr" :fn="fn" /> <div v-else>[{{ l }},{{ r }}]</div> </template>
<script> export default { name: "Demo", props: { l: Number, r: Number, fn: Function, }, computed: { mid() { return (this.l + this.r) / 2; }, newl() { return this.fn(this.mid) ? this.l : this.mid; }, newr() { return this.fn(this.mid) ? this.mid : this.r; }, }, }; </script>
|
使用
1
| <demo :l="0" :r="1" :fn="(x) => x > 0" />
|
在线代码
React(能跑)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import React, { Component } from "react";
class App extends Component { demo = (l, r, fn) => { const mid = (l + r) / 2; const newl = fn(mid) ? l : mid; const newr = fn(mid) ? mid : r; if (l !== newl || r !== newr) { return <>{this.demo(newl, newr, fn)}</>; } return ( <div> [{l},{r}] </div> ); };
render() { return <div>{this.demo(this.props.l, this.props.r, this.props.fn)}</div>; } } export default App;
|
使用
1
| <App l={0} r={1} fn={(v) => v > 0} />
|
在线代码
Angular(我本地调也爆栈,但是在线的可以
html
1 2 3 4 5 6 7 8 9 10
| <demo *ngIf="l !== newl() || r !== newr();else ShowResult" [l]="newl()" [r]="newr()" [fn]="fn" > </demo> <ng-template #ShowResult> [{{ l }} , {{ r }}] </ng-template>
|
js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import { Component, Input } from "@angular/core";
@Component({ selector: "demo", templateUrl: "./demo.component.html", styleUrls: ["./demo.component.css"] }) export class DemoComponent { @Input() l: number; @Input() r: number; @Input() fn: (v: number) => boolean;
newl() { const mid: number = (this.l + this.r) / 2; return this.fn(mid) ? this.l : mid; }
newr() { const mid: number = (this.l + this.r) / 2; return this.fn(mid) ? mid : this.r; } }
|
使用
1
| <demo [l]="0" [r]="1" [fn]="fn"> </demo>
|
在线代码
本地一旦把ngIf 去了也能跑,迷。
搜了半天,没学会ng怎么做完全的无wrapper的页面元素。