Skip to content

Commit

Permalink
chore(playground): bubble sort
Browse files Browse the repository at this point in the history
  • Loading branch information
dntzhang committed Jul 16, 2022
1 parent 55d9888 commit 76e74c2
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 1 deletion.
90 changes: 90 additions & 0 deletions packages/playground/examples/bubble-sort.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
async function bubbleSort(arr, options) {
const max = arr.length - 1
for (let j = 0; j < max; j++) {
let done = true
for (let i = 0; i < max - j; i++) {
options.check(i, i + 1)
if (arr[i] > arr[i + 1]) {
await swap(arr, i, i + 1)
done = false
}
}
if (done) {
options.done(arr)
break
}
}
return arr
}

function swap(arr, indexA, indexB) {
return new Promise(resolve => {
setTimeout(() => {
const temp = arr[indexA];
arr[indexA] = arr[indexB]
arr[indexB] = temp
resolve()
}, 20)
})
}

class Store {
data = {
arr: [2, 7, 12, 9, 16, 19, 8, 13, 11, 5, 15, 17, 14, 18, 6, 3, 10, 1, 4],
indexA: -1,
indexB: -1,
sorting: false
}
sort = () => {
this.data.sorting = true
bubbleSort(this.data.arr, {
done: () => {
this.data.indexA = -1
this.data.indexB = -1
this.ui.update()
},
check: (indexA, indexB) => {
this.data.indexA = indexA
this.data.indexB = indexB
this.ui.update()
}
})
}
}

@tag('my-element')
class extends WeElement {
static css = `
.bar {
display: inline-block;
margin-left: 1px;
background: #777;
width: 10px;
}
.active{
background: red;
}`

installed() {
this.store.ui = this
}

render(prop, store) {
return (
<div>
<div>
{store.data.arr.map((item, index) => (
<div class={classNames('bar', {
'active': index === store.data.indexA || index === store.data.indexB
})} style={{ height: item * 10 }}></div>
))}
</div>

<button disabled={store.data.sorting} onClick={store.sort}>Start Bubble Sort</button>
</div>
)
}
}

render(<my-element />, 'body', new Store)
3 changes: 2 additions & 1 deletion packages/playground/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@
<li class="button" data-example="hello-omi">Hello OMI</li>
<li class="button" data-example="slot">Slot</li>
<li class="button" data-example="fragment">Fragment</li>
<li class="button" data-example="unsafe-html">UnsafeHTML</li>
<li class="button" data-example="unsafe-html">Unsafe HTML</li>
<li class="button" data-example="bubble-sort">Bubble Sort</li>
<!--
<li class="button" data-example="async-generators">
Async generators
Expand Down
1 change: 1 addition & 0 deletions packages/playground/preview.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
var render = Omi.render;
var h = Omi.h;
var tag = Omi.tag;
var classNames = Omi.classNames;
// 不生效, 所以设置一下 React
// jsxFragment: 'h.f',
// jsxFragmentFactory: 'h.f',
Expand Down

0 comments on commit 76e74c2

Please sign in to comment.