在JavaScript中,类定义不会像函数一样被提升,这意味着在使用之前已经定义了一个类,或者在这种情况下,已经扩展了类。
我有一个类列表,其中一些是扩展的,有些则不是。
class G
class F extends A
class B
class A extends D
class E
class C extends D
class D
我想对它进行排序,看起来像这样:
class B
class D
class E
class G
class A extends D
class F extends A
class C extends D
假设我们有一个如下所示的数组:
myClasses = [{
className: 'A',
extendsClass: 'B'
}...and so on]
我开始只取出所有非扩展类并将其放在结果中,但是当我进入扩展的类时,我不知道如何推理......
如何将数组排序为正确的顺序,以便我可以在定义后扩展类?
谢谢!
答案 0 :(得分:0)
这可能会有所帮助,它使用了数组排序功能和一个非常难看的比较函数:
const parseClasses = classes =>
classes
.split ("\n")
.map (x => x.replace ("class", ""))
.map (x => x.split ("extends"))
.map (xs => xs.map (x => x.replace (/ /g, "")))
.map (xs => xs.length > 1
? ({className : xs[0], extendsClass: xs[1]})
: ({className : xs[0]}))
const compare = (a, b) =>
(a.extendsClass && b.extendsClass
? (a.className == b.extendsClass
? -1
: (b.className == a.extendsClass
? 1
: (a.extendsClass.localeCompare (b.extendsClass) == 0
? a.className.localeCompare (b.className)
: a.extendsClass.localeCompare (b.extendsClass))))
: (a.extendsClass
? 1
: (b.extendsClass
? -1
: a.className.localeCompare (b.className))))
console.log ("Classes A: ")
const classesA = `class G
class F extends A
class B
class A extends D
class E
class C extends D
class D`
const myClassesA = parseClasses (classesA)
myClassesA.sort (compare)
console.log (myClassesA)
console.log ()
console.log ("Classes B: ")
const classesB = `class G
class F extends A
class B
class A extends D
class E
class C extends F
class Y extends F
class Z extends F
class Q extends F
class M extends Q
class X extends M
class U extends Z
class D`
const myClassesB = parseClasses (classesB)
myClassesB.sort (compare)
console.log (myClassesB)