56 lines
1.8 KiB
JavaScript
56 lines
1.8 KiB
JavaScript
import React from 'react';
|
|
import './Fauxbonacci.css';
|
|
|
|
export default class Fauxbonacci extends React.Component {
|
|
|
|
constructor(props) {
|
|
super(props);
|
|
this.state = {i: ""};
|
|
}
|
|
|
|
//pretty implementation but slooow.
|
|
prettyButSlowFindByIndex(i) {
|
|
i = parseInt(i);
|
|
if(isNaN(i) || i < 0) return "";
|
|
if(i === 0) return 7;
|
|
if(i === 1) return 5;
|
|
return this.findByIndex(i - 1) + this.findByIndex(i - 2);
|
|
}
|
|
|
|
//much faster, but without proper tail calls, it still explodes the
|
|
// callstack sometime before i == 10000 but by then the result isn't
|
|
// very accurate due to limitation of javascript Number.
|
|
fasterFindByIndex(i) {
|
|
if(i < 0 ) return "Range error...";
|
|
if(i === 0) return 7;
|
|
if(i === 1) return 5;
|
|
|
|
let answer = "Does not compute!";
|
|
try {
|
|
answer = this.findByIndexHelper(i);
|
|
} catch(e) {
|
|
console.error(e);
|
|
}
|
|
return answer;
|
|
}
|
|
|
|
findByIndexHelper(i, before = 5, beforeBefore = 7, runningIndex = 2) {
|
|
if(i === runningIndex) {
|
|
return before + beforeBefore;
|
|
}
|
|
return this.findByIndexHelper(i, before + beforeBefore, before, runningIndex + 1);
|
|
}
|
|
|
|
render() {
|
|
const safeI = parseInt(this.state.i);
|
|
const result = isNaN(safeI) ? "" : this.fasterFindByIndex(safeI);
|
|
const exact = !result || result < Number.MAX_SAFE_INTEGER;
|
|
|
|
return <div className="card mt-3"><div className="card-body faux-component">
|
|
<p>the interviewer requested a component that could accept a the index of a fibonacci sequence that started with 7 and 5 and output the value at that index in the sequence.</p>
|
|
<span className="faux-big-n">N</span><sub><input className="faux-number-input" onChange={(e) => this.setState({i: e.target.value})}/></sub>{exact ? "=" : String.fromCharCode(0x2248)} {result}
|
|
</div></div>
|
|
}
|
|
}
|
|
|