Skip to content

Instantly share code, notes, and snippets.

@branneman
Created October 17, 2022 19:47
Show Gist options
  • Save branneman/721a1b6b18d9a8fac5b0baaec98c6a3c to your computer and use it in GitHub Desktop.
Save branneman/721a1b6b18d9a8fac5b0baaec98c6a3c to your computer and use it in GitHub Desktop.
Interfaces
// Interface of a primitive variable: its name and type
const DEFAULT_DB_HOST = 'localhost'
// Interface of a container variable: its name, types and structures
const config = {
user: 'readuser',
pass: '******',
db: 'test-env',
}
// Interface of a function: its name, arguments and types, return type
/**
* @param {Function} fn
* @param {Array} list
* @returns {Boolean}
*/
const every = (fn, list) => {
var idx = 0
while (idx < list.length) {
if (!fn(list[idx])) return false
idx += 1
}
return true
}
// Interface of a class: its name, static variables/functions, constructor function,
// other functions (and all their arguments and types and return types)
class StrategyAttributeAdapterIteratorSetterBridgeTestMockSerializer { // 😛 https://projects.haykranen.nl/java/
static defaultConfig = {
host: 'localhost',
}
static clone() {
return new this.constructor(this.config)
}
constructor(config) {
this.config = config
}
connect() { /* ... */ }
}
//
// Consumer of sum()
// the 'call site'
// lib/module.js
//
import { sum } from '../util/math.js'
const result = sum(1300, 37)
console.log(result)
//
// Implementation of sum()
// util/math.js
// Interface of sum: name, arguments (name, type), return type
//
export const sum = (a, b) => { /* ... */ }
const { inspect } = require('util')
const log = (x) => console.log(inspect(x, { depth: null, colors: true }))
const Tree = class {
constructor(item, children) {
this.item = item
this.children = children
}
map(fn) {
const val = fn(this.item)
if (!this.children || !this.children.length) {
return new Tree(val, [])
}
return new Tree(
val,
this.children.map((x) => {
const t = new Tree(x.item, x.children)
return t.map(fn)
})
)
}
}
const versions = new Tree('1.1.1', [
new Tree('1.1.0', [new Tree('1.1.1'), new Tree('1.1.2')]),
new Tree('1.2.0', [new Tree('1.2.1')]),
new Tree('1.3.0', []),
])
const result = versions.map((x) => 'v' + x)
log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment