Skip to content

Instantly share code, notes, and snippets.

@farishan
Created April 15, 2023 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farishan/7937039a5c76421ac9534609777793b2 to your computer and use it in GitHub Desktop.
Save farishan/7937039a5c76421ac9534609777793b2 to your computer and use it in GitHub Desktop.
Execute object's method from text input
const object = {
help: function () {
console.log(`Object keys: ${Object.keys(this).filter(k => !k.includes('_')).join(', ')}`)
},
emit: function (payload) {
console.log(payload.join(' '))
},
_private: function () {
console.log('private')
}
}
function MethodTextInterface() {
let target = undefined
const input = document.createElement('input')
this.setTarget = function (targetObject) {
if (typeof targetObject !== 'object') return
target = targetObject
}
this.getDom = function () {
return input
}
function handler(input, target) {
if (!input || !target) return
const words = input.split(' ')
const firstWord = words[0]
const isFirstWordPublic = firstWord.includes('_') === false
const haveFirstWord = target[firstWord]
const firstWordIsFunction = typeof target[firstWord] === 'function'
if (haveFirstWord && isFirstWordPublic && firstWordIsFunction) {
const restWords = words.slice(1, words.length)
// execute target object's method, pass rest of the words
target[firstWord](restWords)
}
return { input, target }
}
input.placeholder = 'type "help"'
input.onkeydown = function (e) {
if (e.key === 'Enter') {
handler(this.value, target)
}
}
return this
}
const game = {
createElement: function (key) {
let element
if (key === 'method-text-interface') {
element = new MethodTextInterface()
}
return element
}
}
const methodTextInterface = game.createElement('method-text-interface')
methodTextInterface.setTarget(object)
console.log(methodTextInterface)
document.body.appendChild(methodTextInterface.getDom())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment